import React, { useEffect } from "react";

import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

import { ClassicEditor, UnlayerEditor } from "types/unlayer";

import { unlayerOptions } from "../../constants";
import {
  defaultUnlayerScriptUrl,
  komiHostedUnlayerScriptUrl,
} from "constants/unlayer";

import { loadScript } from "./loadScript";
import { createClassicTemplate } from "../utils";

import classnames from "classnames";
import "./ImportedEmailEditor.scss";

export interface ImportedEmailEditorProps
  extends React.HTMLProps<HTMLDivElement> {
  emailEditor: ClassicEditor | null;
  html: string;
  onHtmlChange: (html: string) => void;
  setIsLoading: (isLoading: boolean) => void;
  setEmailEditor: (editor: UnlayerEditor) => void;
}

export const ImportedEmailEditor: React.FC<ImportedEmailEditorProps> = ({
  emailEditor,
  html,
  onHtmlChange,
  setEmailEditor,
  setIsLoading,
  ...props
}) => {
  const isModifiedUnlayerScript = useFeatureIsOn(
    FLAGS.FIX_CRM_675_TEMPLATE_IMPORT_HTML_UX,
  );
  const resolvedHtml = html || "<div />";

  const handleEditorLoaded = () => {
    setIsLoading(false);
  };

  // Loads the script and the editor from Unlayer
  useEffect(() => {
    // Load the editor once the script is loaded
    const loadEditor = () => {
      const editor = window.unlayer?.createEditor({
        id: "editor",
        ...unlayerOptions,
      });
      editor?.loadDesign(createClassicTemplate(resolvedHtml));

      editor?.addEventListener("design:updated", () => {
        editor.exportHtml(({ html }) => onHtmlChange(html));
      });
      editor?.addEventListener("design:loaded", handleEditorLoaded);

      setEmailEditor(editor);
    };

    // Load the script on mount
    if (window.unlayer && emailEditor) {
      emailEditor.loadDesign(createClassicTemplate(resolvedHtml));

      emailEditor.addEventListener("design:updated", () => {
        emailEditor.exportHtml(({ html }) => onHtmlChange(html));
      });
      emailEditor.addEventListener("design:loaded", handleEditorLoaded);
    } else {
      loadScript(
        loadEditor,
        isModifiedUnlayerScript
          ? komiHostedUnlayerScriptUrl
          : defaultUnlayerScriptUrl,
      );
    }
  }, [html, resolvedHtml]);

  const classNames = classnames("imported-template--email-editor");

  return <div {...props} className={classNames} id="editor" />;
};
