import { useEffect, useMemo, useRef, useState } from "react";
import { Editor } from "@tinymce/tinymce-react";
import type { Editor as TinyMCEEditor } from "tinymce";

import "tinymce/tinymce";
import "tinymce/icons/default";
import "tinymce/themes/silver";
import "tinymce/models/dom/model";

// Plugins
import "tinymce/plugins/autolink";
import "tinymce/plugins/link";
import "tinymce/plugins/lists";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/image";
import "tinymce/plugins/preview";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/wordcount";
// fontsize and fontfamily are built into TinyMCE 7 core — they are toolbar
// buttons, not plugins. Do not list them under plugins.

// CSS
import "tinymce/skins/ui/oxide/skin.min.css";
import "tinymce/skins/ui/oxide-dark/skin.min.css";

export default function RichTextEditor({
  value,
  onChange,
  shouldClear,
}: {
  value?: string;
  onChange?: (v: string) => void;
  shouldClear?: boolean;
}) {
  const editorRef = useRef<TinyMCEEditor | null>(null);
  const [isDarkMode, setIsDarkMode] = useState(() => {
    if (typeof window === "undefined") {
      return false;
    }

    const root = document.documentElement;
    return (
      root.classList.contains("dark") || root.getAttribute("data-theme") === "dark"
    );
  });

  // ✅ When shouldClear becomes true → clear editor + remove draft
  useEffect(() => {
    if (shouldClear) {
      if (editorRef.current) {
        editorRef.current.setContent("");
      }
    }
  }, [shouldClear]);

  useEffect(() => {
    const root = document.documentElement;
    const updateThemeMode = () => {
      setIsDarkMode(
        root.classList.contains("dark") ||
          root.getAttribute("data-theme") === "dark",
      );
    };

    updateThemeMode();

    const observer = new MutationObserver(updateThemeMode);
    observer.observe(root, {
      attributes: true,
      attributeFilter: ["class", "data-theme"],
    });

    return () => {
      observer.disconnect();
    };
  }, []);

  const init = useMemo(
    () => ({
      // Point self-hosted TinyMCE at the static assets copied into /public/tinymce.
      // Without this, the bundled TinyMCE has an empty baseURL and resolves
      // skin/content CSS against the current page URL, producing 404s like
      // /record-management/userRecords//skins/ui/oxide/skin.css on deep routes.
      base_url: "/tinymce",
      suffix: ".min",
      height: 480,
      menubar: true,
      plugins:
        "autolink link lists code table image preview searchreplace wordcount",
      toolbar: [
        "| fontfamily fontsize",
        "undo redo | styles | bold italic underline |",
        "alignleft aligncenter alignright alignjustify |",
        "bullist numlist outdent indent | link image table | code preview ",
      ].join(" "),
      skin: isDarkMode ? "oxide-dark" : "oxide",
      content_css: false,
      promotion: false,
      content_style: `
        body {
          background-color: ${isDarkMode ? "#0f172a" : "#ffffff"};
          color: ${isDarkMode ? "#e2e8f0" : "#0f172a"};
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
          line-height: 1.4;
          margin: 1rem;
        }
        a {
          color: ${isDarkMode ? "#93c5fd" : "#2563eb"};
        }
        table {
          border-collapse: collapse;
        }
        table, th, td {
          border-color: ${isDarkMode ? "#475569" : "#cbd5e1"};
        }
        table:not([cellpadding]) td, table:not([cellpadding]) th {
          padding: 0.4rem;
        }
        table[border]:not([border="0"]):not([style*="border-width"]) td,
        table[border]:not([border="0"]):not([style*="border-width"]) th {
          border-width: 1px;
        }
        table[border]:not([border="0"]):not([style*="border-style"]) td,
        table[border]:not([border="0"]):not([style*="border-style"]) th {
          border-style: solid;
        }
        code {
          background-color: ${isDarkMode ? "#334155" : "#e2e8f0"};
          border-radius: 3px;
          padding: 0.1rem 0.2rem;
        }
        hr {
          border-color: ${isDarkMode ? "#475569" : "#cbd5e1"};
          border-style: solid;
          border-width: 1px 0 0 0;
        }
        .mce-content-body:not([dir=rtl]) blockquote {
          border-left: 2px solid ${isDarkMode ? "#475569" : "#cbd5e1"};
          margin-left: 1.5rem;
          padding-left: 1rem;
        }
        .mce-content-body[dir=rtl] blockquote {
          border-right: 2px solid ${isDarkMode ? "#475569" : "#cbd5e1"};
          margin-right: 1.5rem;
          padding-right: 1rem;
        }
      `,

      // Fonts (Latin + Amharic/Ethiopic)
      font_family_formats:
        "Arial=arial,helvetica,sans-serif;" +
        "Courier New=courier new,courier,monospace;" +
        "Georgia=georgia,palatino;" +
        "Tahoma=tahoma,arial,helvetica,sans-serif;" +
        "Times New Roman=times new roman,times;" +
        "Verdana=verdana,geneva;" +
        "Roboto=Roboto, sans-serif;" +
        "Open Sans=Open Sans, sans-serif;" +
        "Lato=Lato, sans-serif;" +
        "Montserrat=Montserrat, sans-serif;" +
        "Nyala=Nyala, sans-serif;" + // Windows Amharic font
        "Abyssinica SIL=Abyssinica SIL, serif;" + // Amharic (Linux/Google Fonts)
        "Noto Sans Ethiopic=Noto Sans Ethiopic, sans-serif;" + // Google Fonts Amharic
        "Ebrima=Ebrima, sans-serif;" + // Ethiopic, Arabic
        "Sylfaen=Sylfaen, serif;" + // Ethiopic + Armenian/Georgian
        "Geez Able=Geez Able, serif;" + // Common Ethiopic font
        "Visual Geez Unicode=Visual Geez Unicode, serif;" + // Popular for Amharic docs
        "Segoe UI=Segoe UI, sans-serif;" +
        "Helvetica=helvetica,arial,sans-serif;" +
        "Trebuchet MS=Trebuchet MS, sans-serif;" +
        "Garamond=Garamond, serif;" +
        "Cambria=Cambria, serif;" +
        "Calibri=Calibri, sans-serif;",

      // Extended font sizes
      fontsize_formats:
        "8pt 10pt 12pt 14pt 18pt 66pt 24pt 36pt 48pt 72pt " +
        "1em 1.2em 1.5em 2em 3em 4em " +
        "small medium large x-large xx-large",
    }),
    [isDarkMode],
  );

  return (
    <Editor
      key={isDarkMode ? "tinymce-dark" : "tinymce-light"}
      onInit={(_, editor) => (editorRef.current = editor)}
      value={value}
      onEditorChange={onChange}
      init={init}
    />
  );
}
