import { DesignComp } from "@/modules/editor/defines/DesignTemp/DesignComp";
import { css } from "@linaria/core";
import { defineUI } from "queenjs";
import { computed, onUnmounted } from "vue";
import { Container, Draggable } from "vue-dndrop";
import { useEditor } from "../../..";
import { HotKeyCtrl } from "../../../controllers/HotKeyCtrl";
import Canvas from "../../Canvas";
import ErrorComp from "../../CompUI/placeHoder";

export default defineUI({
  setup() {
    const editor = useEditor();
    const { store, actions, config } = editor;

    const hotKeyCtrl = new HotKeyCtrl(editor);
    hotKeyCtrl.init();
    onUnmounted(() => {
      hotKeyCtrl.destroy();
    });

    const compsGroup = computed(() => {
      const normalArr: DesignComp[] = [];
      const posArr: DesignComp[] = [];
      store.designData.content.forEach((d) => {
        if (d.compKey === "Container") {
          posArr.push(d);
        } else {
          normalArr.push(d);
        }
      });
      console.log(normalArr, posArr);
      return {
        normalArr,
        posArr,
      };
    });

    return () => (
      <div class={contentStyle}>
        <div class="relative z-10">
          {compsGroup.value.posArr.map((d) => {
            const Comp: any = config.compUI[d.compKey]?.Component;
            return Comp ? <Comp key={d.id} compId={d.id} /> : undefined;
          })}
        </div>
        {store.isEditMode ? (
          <Container
            style={store.designData.pageStyle}
            onDrop={(e: any) => actions.moveComp(e.removedIndex, e.addedIndex)}
            non-drag-area-selector={".drag-disable"}
          >
            {compsGroup.value.normalArr.map((d) => {
              const Comp: any =
                config.compUI[d.compKey]?.Component || ErrorComp;
              return (
                <Draggable key={d.id}>
                  <Comp compId={d.id} />
                </Draggable>
              );
            })}
          </Container>
        ) : (
          <Canvas />
        )}
      </div>
    );
  },
});

const contentStyle = css`
  position: relative;
  border: 1px solid transparent;
  @apply min-h-750px bg-white;

  .dndrop-container.vertical > .dndrop-draggable-wrapper {
    overflow: unset;
  }
`;
