import { Icon } from "@iconify/react"
import { Button, DropdownMenu } from "@ivtui/base"

interface DropdownProps {
  options: { label: string; value: string }[]
  value: string
  onChange: (value: string) => void
  placeholder: string
  disabled?: boolean
  size?: "1" | "2" | "3"
  title?: string
}

export function Dropdown({
  options,
  value,
  onChange,
  placeholder,
  disabled,
  size = "2",
  title,
}: React.PropsWithChildren<DropdownProps>) {
  const selectedOption = options.find(opt => opt.value === value)

  const handleOptionSelect = (optionValue: string) => {
    if (!disabled && optionValue !== value) {
      onChange(optionValue)
    }
  }

  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger>
        <Button variant="soft" color="gray" size={size} disabled={disabled} title={title}>
          <span>{selectedOption?.label || placeholder}</span>
          <Icon icon="mdi:chevron-down" className="size-4 flex-shrink-0" />
        </Button>
      </DropdownMenu.Trigger>
      <DropdownMenu.Content color="gray" side="bottom" align="start" className="min-w-[120px]">
        {options.map(option => (
          <DropdownMenu.Item
            key={option.value}
            onClick={() => handleOptionSelect(option.value)}
            className={option.value === value ? "bg-gray-100" : ""}
          >
            {option.label}
            {option.value === value && <Icon icon="mdi:check" className="size-4 ml-auto" />}
          </DropdownMenu.Item>
        ))}
      </DropdownMenu.Content>
    </DropdownMenu.Root>
  )
}
