import { useRef, useCallback } from "react"
import { Editor } from "@tinymce/tinymce-react"
import { normalizeHtml } from "../lib/cms-utils"

type Props = {
  value: string
  onChange: (html: string) => void
  placeholder?: string
  label?: string
  required?: boolean
}

const TINYMCE_CDN = "https://cdn.jsdelivr.net/npm/tinymce@7"

export function RichTextEditor({ value, onChange, placeholder, label, required }: Props) {
  const editorRef = useRef<unknown>(null)
  const htmlValue = (typeof value === "string" ? value : "") || ""

  const handleEditorChange = useCallback(
    (newContent: string) => {
      const normalizedNew = normalizeHtml(newContent)
      const normalizedOld = normalizeHtml(htmlValue)
      if (normalizedNew !== normalizedOld) {
        onChange(newContent)
      }
    },
    [onChange, htmlValue]
  )

  return (
    <div className="rich-text-editor">
      {label != null && (
        <span className="text-sm font-medium text-ui-fg-base mb-1 block">
          {label}
          {required ? " *" : ""}
        </span>
      )}
      <div
        className="rich-text-editor-resizable"
        style={{
          minHeight: 200,
          height: 280,
          resize: "vertical",
          overflow: "hidden",
        }}
      >
        <style>{`
          .rich-text-editor-resizable .tox-tinymce { height: 100% !important; }
          .rich-text-editor-resizable .tox .tox-edit-area__iframe { height: 100% !important; }
        `}</style>
        <Editor
          tinymceScriptSrc={`${TINYMCE_CDN}/tinymce.min.js`}
          onInit={(_evt, editor) => {
            editorRef.current = editor
          }}
          value={htmlValue}
          onEditorChange={handleEditorChange}
          init={{
            licenseKey: "gpl",
            height: "100%",
            menubar: false,
            placeholder: placeholder ?? "Start typing...",
            skin_url: `${TINYMCE_CDN}/skins/ui/oxide`,
            content_css: false,
            plugins: [
              "advlist",
              "autolink",
              "lists",
              "link",
              "charmap",
              "anchor",
              "searchreplace",
              "visualblocks",
              "code",
              "fullscreen",
              "insertdatetime",
              "table",
              "help",
              "wordcount",
            ],
            toolbar:
              "undo redo | blocks | bold italic underline forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | link | code | help",
            content_style:
              "body { font-family: Helvetica, Arial, sans-serif; font-size: 14px; }",
            branding: false,
            promotion: false,
          }}
        />
      </div>
    </div>
  )
}
