import { IconPlay2 } from "@/assets/icons";
import { useEditor } from "@/modules/editor";
import { css } from "@linaria/core";
import { IconClose } from "@queenjs/icons";
import { Image } from "@queenjs/ui";
import { queenApi, useModal } from "queenjs";
import { defineComponent, reactive, watch } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { View } from "../View";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const { store, actions } = useEditor();
    const comp = useCompData(props.compId);
    const { value } = comp;

    async function pickPack() {
      // await controls.pickCtrl.onPickPack();
      // value.url =
      //   "https://www.sku3d.com/share.html?id=6478676ca494a3ea15a6fa82";
    }

    function showWeb3D() {
      if (value.inline) {
        state.show3d = true;
      } else {
        queenApi.dialog(<Iframe3D url={value.url} />, {
          fullscreen: true,
          closable: false,
        });
      }
    }

    const state = reactive({
      show3d: false,
    });

    watch(
      () => [value.ratio],
      () => {
        comp.setH(comp.getW() / value.ratio);
        actions.onCompLayoutUpdated(comp);
      }
    );

    return () => {
      return (
        <View
          compId={props.compId}
          onDblclick={store.isEditMode ? pickPack : undefined}
        >
          {state.show3d ? (
            <iframe class="w-full h-full border-none" src={value.url} />
          ) : (
            <>
              <Image
                class="w-full h-full pointer-events-none object-cover"
                size={480}
                src={value.poster}
              />
              <IconPlay2
                class={iconCls}
                onClick={!store.isEditMode ? showWeb3D : undefined}
              />
            </>
          )}
        </View>
      );
    };
  },
});

const Iframe3D = defineComponent({
  props: {
    url: string().isRequired,
  },
  setup(props) {
    const modal = useModal();
    return () => (
      <div class="w-full h-full overflow-hidden relative">
        <IconClose class={closeCls} onClick={() => modal.cancel()} />
        <iframe class="w-full h-full border-none" src={props.url} />
      </div>
    );
  },
});

const iconCls = css`
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 15px;
  font-size: 50px;
  color: #666;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.7);
`;

const closeCls = css`
  position: absolute;
  top: 15px;
  left: 15px;
  font-size: 15px;
  color: #666;
  padding: 10px;
  border-radius: 50%;
  background-color: #fff;
  @apply shadow;
`;
