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

interface ColorControlProps {
  editor: Editor
}

const predefinedColors = [
  "#000000",
  "#333333",
  "#666666",
  "#999999",
  "#cccccc",
  "#ffffff",
  "#ff0000",
  "#ff6600",
  "#ffcc00",
  "#00ff00",
  "#0066ff",
  "#6600ff",
  "#ff0066",
  "#ff3366",
  "#ff6699",
  "#66ff00",
  "#00ff66",
  "#0066cc",
  "#6600cc",
  "#cc00ff",
  "#ff00cc",
  "#cc6600",
  "#ffcc66",
  "#66ccff",
]

export function ColorControl({ editor }: React.PropsWithChildren<ColorControlProps>) {
  const [currentColor, setCurrentColor] = useState("#000000")
  const [open, setOpen] = useState(false)

  // Get current text color from editor
  useEffect(() => {
    const updateColor = () => {
      const colorMark = editor.getAttributes("textStyle")
      if (colorMark.color) {
        setCurrentColor(colorMark.color)
      }
    }

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

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

  const handleColorChange = (color: string) => {
    setCurrentColor(color)
    editor.chain().focus().setColor(color).run()
    setOpen(false)
  }

  const handleRemoveColor = () => {
    setCurrentColor("#000000")
    editor.chain().focus().unsetColor().run()
    setOpen(false)
  }

  return (
    <Popover.Root open={open} onOpenChange={setOpen}>
      <Popover.Trigger>
        <IconButton
          variant="ghost"
          size="1"
          color="gray"
          title="Text Color"
          className="flex items-center gap-1"
        >
          <div className="flex flex-col items-center">
            <Icon icon="mdi:format-color-text" className="size-5" />
            <div
              className="w-4 h-1 rounded-sm border border-gray-300"
              style={{ backgroundColor: currentColor }}
            />
          </div>
          <Icon icon="mdi:chevron-down" className="size-3 text-gray-500" />
        </IconButton>
      </Popover.Trigger>

      <Popover.Content className="w-50 p-3" side="bottom" align="start">
        <div className="grid grid-cols-6 gap-1 mb-3">
          {predefinedColors.map(color => (
            <IconButton
              key={color}
              variant="outline"
              color="gray"
              size="1"
              onClick={() => handleColorChange(color)}
              title={color}
              className=" hover:!scale-110 transition-transform"
              style={{ backgroundColor: color }}
            />
          ))}
        </div>
        <div className="flex gap-2">
          <Button
            variant="soft"
            color="gray"
            size="1"
            onClick={handleRemoveColor}
            className="text-xs"
          >
            Remove Color
          </Button>
        </div>
      </Popover.Content>
    </Popover.Root>
  )
}
