import React, { useMemo, useState, useEffect } from "react";
import { Editor as TinyMCEEditor } from "@/record-management/common/editor/rte";
import type { Editor as TinyMCEEditorType } from "tinymce";

export interface Placeholder {
  key: string;
  label: string;
}

interface TemplateEditorProps {
  value: string;
  onEditorChange: (value: string, editor: TinyMCEEditorType) => void;
  apiKey?: string;
  placeholders?: Placeholder[];
}

export const TemplateEditor: React.FC<TemplateEditorProps> = ({
  value,
  onEditorChange,
  apiKey,
  placeholders,
}) => {
  const hasPlaceholders = placeholders && placeholders.length > 0;
  const [isDarkMode, setIsDarkMode] = useState(() => 
    typeof window !== "undefined" && document.documentElement.classList.contains("dark")
  );
  
  useEffect(() => {
    const observer = new MutationObserver(() => {
      setIsDarkMode(document.documentElement.classList.contains("dark"));
    });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
    return () => observer.disconnect();
  }, []);
  
  const init = useMemo(() => {
    return {
      height: 600,
      menubar: true,
      skin: isDarkMode ? "oxide-dark" : "oxide",
      skin_url: isDarkMode ? "/tinymce/skins/ui/oxide-dark" : "/tinymce/skins/ui/oxide",
      content_css: isDarkMode ? "dark" : "default",
      content_style: `
        body { 
          font-family:Helvetica,Arial,sans-serif; 
          font-size:14px;
          ${isDarkMode ? `
            background-color: #1f2937;
            color: #e5e7eb;
          ` : `
            background-color: #ffffff;
            color: #1f2937;
          `}
        }
        ${hasPlaceholders ? `
          .placeholder {
            ${isDarkMode ? `
              background-color: #065f46;
              border: 1px dashed #34d399;
              color: #a7f3d0;
            ` : `
              background-color: #ecfdf5;
              border: 1px dashed #0EA371;
            `}
            padding: 2px 4px;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
            margin: 0 2px;
          }
        ` : ""}
      `,
      plugins: [
        "autolink", "link", "lists", "code", "table", "image", "preview", "searchreplace", "wordcount",
        ...(hasPlaceholders ? ["noneditable"] : [])
      ].join(" "),
      toolbar: [
        "undo redo | bold italic underline |",
        "alignleft aligncenter alignright alignjustify |",
        "bullist numlist outdent indent | link image table | code preview",
        hasPlaceholders ? "| placeholders" : ""
      ].join(" "),
      noneditable_class: "mceNonEditable",
      setup: (editor: TinyMCEEditorType) => {
        if (hasPlaceholders) {
          editor.ui.registry.addMenuButton("placeholders", {
            text: "Placeholders",
            fetch: (callback) => {
              const items = placeholders.map((p) => ({
                type: "menuitem" as const,
                text: p.label,
                onAction: () => {
                  const html = `<span class="mceNonEditable placeholder" data-key="${p.key}">{{${p.key}}}</span>&#8203;`;
                  editor.insertContent(html);
                },
              }));
              callback(items);
            },
          });

          editor.on("click", (e) => {
            const target = e.target as HTMLElement;
            if (target.classList.contains("placeholder")) {
              editor.selection.select(target);
            }
          });

          editor.on("keydown", (e) => {
            if (e.key === "Backspace" || e.key === "Delete") {
              const node = editor.selection.getNode();
              if (node && node.classList.contains("placeholder")) {
                e.preventDefault();
                node.remove();
              }
            }
          });
        }
      },
    };
  }, [placeholders, hasPlaceholders, isDarkMode]);

  return (
    <TinyMCEEditor
      key={isDarkMode ? "dark" : "light"}
      tinymceScriptSrc="/tinymce/tinymce.min.js"
      apiKey={apiKey}
      value={value}
      onEditorChange={onEditorChange}
      init={init}
    />
  );
};
