import { Icon } from "@iconify/react"
import { IconButton } from "@ivtui/base"
import type { Editor } from "@tiptap/react"
import { useEffect, useState } from "react"

interface FontSizeControlProps {
  editor: Editor
  min?: number
  max?: number
}

export function FontSizeControl({
  editor,
  min = 8,
  max = 72,
}: React.PropsWithChildren<FontSizeControlProps>) {
  const [fontSize, setFontSize] = useState(14)

  // Get current font size from editor
  useEffect(() => {
    const updateFontSize = () => {
      const { from, to } = editor.state.selection
      const marks = editor.state.doc.rangeHasMark(from, to, editor.schema.marks.textStyle)
      if (marks) {
        const textStyleMark = editor.getAttributes("textStyle")
        if (textStyleMark.fontSize) {
          const size = Number.parseInt(textStyleMark.fontSize.replace("px", ""), 10)
          if (!Number.isNaN(size)) {
            setFontSize(size)
          }
        }
      }
    }

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

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

  const handleDecrease = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault()
    event.stopPropagation()
    const newSize = Math.max(min, fontSize - 1)
    setFontSize(newSize)
    editor.chain().focus().setFontSize(`${newSize}px`).run()
  }

  const handleIncrease = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault()
    event.stopPropagation()
    const newSize = Math.min(max, fontSize + 1)
    setFontSize(newSize)
    editor.chain().focus().setFontSize(`${newSize}px`).run()
  }

  return (
    <div className="flex h-8 items-center border border-gray-300 rounded-lg bg-gray-50 px-2">
      <IconButton variant="ghost" color="gray" onClick={handleDecrease} disabled={fontSize <= min}>
        <Icon icon="mdi:minus" />
      </IconButton>
      <span className="px-3 text-sm font-medium min-w-[28px] text-center">{fontSize}</span>
      <IconButton variant="ghost" color="gray" onClick={handleIncrease} disabled={fontSize >= max}>
        <Icon icon="mdi:plus" />
      </IconButton>
    </div>
  )
}
