import {
  h, Component, useRef, useEvent,
} from "atomico";
import "../kun-icon/kun-icon";
import { ReqUpLoadMarkdown, updateMarkdown } from "@caedman/seek-api/build/api/upload-markdown";
import style from "./kun-markdown-button.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { execWithSixLoad } from "../../common/exec-confirm";

const KunMarkdownButton = () => {
  const refLabel = useRef<HTMLButtonElement>();

  const uploadMarkdownEvent = useEvent("MyUpload", {
    bubbles: true,
    composed: true,
  });
  const uploadFile = async (event): Promise<void> => {
    await execWithSixLoad(async () => {
      const file = event.target.files[0];
      const formData = new FormData();
      formData.set("file", file);
      const r = await updateMarkdown(formData as ReqUpLoadMarkdown);
      uploadMarkdownEvent({ content: r.record.content });
    });
  };

  return (
    <host>
      <style>{style}</style>
      <span>
        <kun-icon iconType="markdown" onclick={() => refLabel.current.click()} iconWidth={24} iconHeight={24} />
        <input ref={refLabel} type="file" className="hidden" onchange={uploadFile} />
      </span>
    </host>
  );
};

KunMarkdownButton.props = {
};

export default getComponentOrDefine("kun-markdown-button", KunMarkdownButton);
