import { useEditor } from "@/modules/editor";
import { Alignment } from "@ckeditor/ckeditor5-alignment";
import { Bold, Italic } from "@ckeditor/ckeditor5-basic-styles";
import { InlineEditor } from "@ckeditor/ckeditor5-editor-inline";
import { Essentials } from "@ckeditor/ckeditor5-essentials";
import { FontColor, FontFamily, FontSize } from "@ckeditor/ckeditor5-font";
import { Link } from "@ckeditor/ckeditor5-link";
import { Paragraph } from "@ckeditor/ckeditor5-paragraph";
import { css } from "@linaria/core";
import { reactive } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { createUIComp } from "../../defines/createUIComp";

export const Component = createUIComp({
  props: {
    compId: string(),
    value: string().def(""),
  },
  emits: ["update:value"],
  setup(props, { emit }) {
    const comp = props.compId ? useCompData(props.compId) : null;
    const { store } = useEditor();
    const config = {
      plugins: [
        Essentials,
        Bold,
        Italic,
        Link,
        Paragraph,
        FontColor,
        FontSize,
        FontFamily,
        Alignment,
      ],
      fontSize: {
        options: [12, 14, 16, 18, 20, 24, 28, 32, 38,42, 46],
      },
      toolbar: {
        items: [
          // "undo",
          // "redo",
          // "|",
          "fontColor",
          "fontsize",
          "bold",
          "italic",
          "|",
          "alignment",
          // "|",
          // "link",
        ],
      },
    };

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

    return () => (
      <div class={["w-1/1 h-1/1", state.focus && "drag-disable"]}>
        <ckeditor
          class={textStyle}
          editor={InlineEditor}
          onBlur={(e: any, editor: InlineEditor) => {
            state.focus = false;
            if (comp) {
              comp.value = editor.getData();
            } else {
              emit("update:value", editor.getData());
            }
          }}
          onFocus={() => (state.focus = true)}
          onReady={(editor: InlineEditor) => {
            editor.setData(comp?.value || props.value);
            if (!store.isEditMode) {
              editor.enableReadOnlyMode("editor");
            }
          }}
          config={config}
        />
      </div>
    );
  },
});

const textStyle = css`
  font-size: 0.14rem;
  p {
    margin: 0;
  }
  &.ck.ck-editor__editable_inline {
    > :last-child,
    > :first-child {
      margin-top: 0;
      margin-bottom: 0;
    }
  }
`;
