import { useState, useEffect, useRef, type ReactNode } from 'react'
import styles from './Dropdown.module.css'

export interface DropdownItem {
  label: string
  icon?: ReactNode
  onClick?: () => void
  divider?: boolean
  disabled?: boolean
}

interface DropdownProps {
  trigger: ReactNode
  items: DropdownItem[]
  className?: string
}

export function Dropdown({ trigger, items, className }: DropdownProps) {
  const [open, setOpen] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  // Close on outside click
  useEffect(() => {
    if (!open) return
    function handleClick(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [open])

  // Close on Esc
  useEffect(() => {
    if (!open) return
    function handleKey(e: KeyboardEvent) {
      if (e.key === 'Escape') setOpen(false)
    }
    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [open])

  function handleItemClick(item: DropdownItem) {
    if (item.disabled) return
    item.onClick?.()
    setOpen(false)
  }

  return (
    <div ref={containerRef} className={`${styles.container} ${className ?? ''}`}>
      <div
        className={styles.trigger}
        onClick={() => setOpen((prev) => !prev)}
      >
        {trigger}
      </div>
      {open && (
        <ul className={styles.menu} role="menu">
          {items.map((item, index) => {
            if (item.divider) {
              return <li key={index} className={styles.divider} role="separator" />
            }
            return (
              <li key={index} role="menuitem">
                <button
                  className={`${styles.menuItem} ${item.disabled ? styles.disabled : ''}`}
                  onClick={() => handleItemClick(item)}
                  disabled={item.disabled}
                  type="button"
                >
                  {item.icon && <span className={styles.icon}>{item.icon}</span>}
                  <span>{item.label}</span>
                </button>
              </li>
            )
          })}
        </ul>
      )}
    </div>
  )
}
