import type { Editor } from "@tiptap/react"
import { useEffect, useState } from "react"
import { Dropdown } from "./Dropdown"

interface FontFamilyControlProps {
  editor: Editor
}

const fontFamilyOptions = [
  { label: "Arial", value: "Arial, sans-serif" },
  { label: "Times New Roman", value: "Times New Roman, serif" },
  { label: "Helvetica", value: "Helvetica, sans-serif" },
  { label: "Georgia", value: "Georgia, serif" },
  { label: "Verdana", value: "Verdana, sans-serif" },
  { label: "Courier New", value: "Courier New, monospace" },
  { label: "System", value: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" },
]

export function FontFamilyControl({ editor }: React.PropsWithChildren<FontFamilyControlProps>) {
  const [fontFamily, setFontFamily] = useState("Arial, sans-serif")

  // Get current font family from editor
  useEffect(() => {
    const updateFontFamily = () => {
      const textStyleMark = editor.getAttributes("textStyle")
      if (textStyleMark.fontFamily) {
        setFontFamily(textStyleMark.fontFamily)
      }
    }

    editor.on("selectionUpdate", updateFontFamily)
    updateFontFamily()

    return () => {
      editor.off("selectionUpdate", updateFontFamily)
    }
  }, [editor])

  const handleFontFamilyChange = (value: string) => {
    setFontFamily(value)
    editor.chain().focus().setFontFamily(value).run()
  }

  return (
    <Dropdown
      options={fontFamilyOptions}
      value={fontFamily}
      onChange={handleFontFamilyChange}
      placeholder="Font"
    />
  )
}
