import {
  h, useEffect, useHost, useRef, useState, useEvent, useProp,
} from "atomico";
import "./tiptap/Components/EditorMenuBarAtomico";
import "../kun-icon/kun-icon";
import "../kun-ex-link/kun-ex-link";
import "../kun-markdown-button/kun-markdown-button";
import "./import-link-dialog/import-link-dialog";
import "./import-url-dialog/import-url-dialog";
import "../kun-checkbox/kun-checkbox";
import { Maybe } from "purify-ts/es/Maybe";
// import style1 from "highlight.js/styles/github.css";
import { useStylesheet } from "@caedman/kit/dist/use-stylesheet";
import style from "./tiptap/style.scss";
import PEditor from "./tiptap/PEditor";
import "../kun-link-button/kun-link-button";
import { requestUploadFile1 } from "./req-upload-file";
import { defaultHtmlStyle } from "./html-style";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function KunEditor() {
  const [defaultContent] = useProp("defaultContent");
  const [hasTitle] = useProp("hasTitle");
  const r = "<p>dddddd</p>";

  console.log("defaultdefaultContentdefaultContent", defaultContent);

  const content = Maybe.fromNullable(defaultContent).orDefault(hasTitle ? "<h1>标题</h1><p>内容</p>" : r);

  const host = useHost();
  const ref = useRef();
  const refMenuBar = useRef();
  const refFile = useRef();
  const refLabel = useRef();
  const updateEditor = useEvent("MyEditorUpdate", { bubbles: true });
  const [editor, setEditor] = useState(null);
  const [showFloat, setShowFloat] = useState(null);
  const [activeState, setActive] = useState({});
  const [htmlContent, setHTMLContent] = useState(content);

  const onSubmitUrl = (event) => {
    const { title, url } = event.detail;
    editor.insertIcon(url, title);
    event.preventDefault();
  };

  const onSubmit = (event) => {
    const data = event.detail;
    const content1 = data.html;
    if (content1 != null) {
      const contentNew = hasTitle ? `<h1>${data.title}</h1>${content1}` : content1;
      editor.setContent(contentNew, true);
    }
  };

  const onMyUploadMarkdown = (event) => {
    const contentNew = `<h1>请填写标题</h1>${event.detail.content}`;
    editor.setContent(contentNew, true);
  };
  const updateImageFile = async (event) => {
    try {
      const file = event.target.files[0];
      const formData = new FormData();
      formData.set("file", file);
      const r = await requestUploadFile1(formData);
      const fileName = `https://file.wintercoming.xyz/${r.msg}`;
      editor?.insertImage?.(fileName);
      console.log("r1", r);
    } catch (e) {
      console.error(e);
    }
  };

  const updateImage = () => {
    console.log("image");
    console.log("ref", refFile);
    refLabel.current.click();
  };
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
  const updateFloatEvt = (name) => {
    if (name === "show") {
      setShowFloat(true);
    } else {
      setShowFloat(false);
    }
  };
  const updateV = ({ getHTML, getJSON, active }) => {
    const html = getHTML();
    const json = getJSON();
    console.log("json", json);
    console.log("html", html);
    setHTMLContent(html);
    updateEditor({ html, json });
    setActive(active);
  };

  useEffect(() => {
    if (host.current != null) {
      const editorInstance = new PEditor(ref.current, updateV, updateFloatEvt, content, hasTitle);
      if (editor == null) {
        setEditor(editorInstance);
      }
      updateEditor({ html: editorInstance.getHTML(), json: editorInstance.getJSON() });
    }
    return () => {
    };
  }, [defaultContent]);

  // TODO style
  const style2 = useStylesheet(defaultHtmlStyle, style);
  return (
    <host shadowDom>
      <style>{style2}</style>
      <div className="editor">
        <div ref={refMenuBar}>
          <div className="header-icons">
            <kun-icon
              iconType="jiacu"
              iconHeight={14}
              iconWidth={14}
              className={activeState.bold ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                  editor?.getC?.()?.bold?.();
              }}
            />
            <kun-icon
              iconType="xieti"
              iconHeight={12}
              iconWidth={12}
              className={activeState.italic ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                    editor?.getC?.()?.italic?.();
              }}
            />

            <kun-icon
              iconType="liebiao"
              iconHeight={14}
              iconWidth={14}
              className={activeState.bullet_list ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                  editor?.getC?.()?.bullet_list?.();
              }}
            />

            <kun-icon
              iconType="youxuliebiao"
              iconHeight={14}
              iconWidth={14}
              className={activeState.ordered_list ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                  editor?.getC?.()?.ordered_list?.();
              }}
            />

            <kun-icon
              iconType="underline"
              iconHeight={14}
              className={activeState.underline ? "editor-menu bg-select" : "editor-menu bg"}
              iconWidth={14}
              onclick={() => {
                  editor?.getC?.()?.underline?.();
              }}
            />

            <kun-icon
              title="yinyong"
              iconType="yinyong"
              iconHeight={14}
              className={activeState.blockquote ? "editor-menu bg-select" : "editor-menu bg"}
              iconWidth={14}
              onclick={() => {
                  editor?.getC?.()?.blockquote?.();
              }}
            />

            <kun-icon
              iconType="tupian"
              iconHeight={14}
              iconWidth={14}
              className={activeState.image ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                console.log("jjjjjj");
                updateImage();
              }}
            />

            <kun-icon
              iconType="h1"
              iconHeight={14}
              iconWidth={14}
              className={editor?.isActive?.heading?.({ level: 1 }) ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                editor?.getC?.()?.heading?.({ level: 1 });
              }}
            />

            <kun-icon
              iconType="h2"
              iconHeight={14}
              iconWidth={14}
              className={editor?.isActive?.heading?.({ level: 2 }) ? "editor-menu bg-select" : "editor-menu bg"}
              onclick={() => {
                editor?.getC?.()?.heading?.({ level: 2 });
              }}
            />

            <kun-icon
              iconType="h3"
              iconHeight={14}
              className={editor?.isActive?.heading?.({ level: 3 }) ? "editor-menu bg-select" : "editor-menu bg"}
              iconWidth={14}
              onclick={() => {
                  editor?.getC?.()?.heading?.({ level: 3 });
              }}
            />

            <kun-import-url-dialog onMyImportUrl={onSubmitUrl} />

            <kun-link-button
              my-selected={editor?.isActive?.link?.()}
              my-url={editor?.getMarkAttrs?.("href")}
              onMyUpdate={(event) => {
                  editor?.insertHref?.(event.detail.url);
              }}
            />

            <kun-markdown-button onMyUpload={onMyUploadMarkdown} />
            <kun-import-link-dialog-1 onMySubmit={onSubmit} />
          </div>
        </div>

        <input ref={refLabel} type="file" className="hidden" onchange={updateImageFile} />
        <div ref={ref} className=" editor__content" />
      </div>
    </host>
  );
}

KunEditor.props = {
  hasTitle: {
    type: Boolean,
    reflect: true,
  },
  defaultContent: {
    type: String,
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

export default getComponentOrDefine("kun-editor", KunEditor);
