import { useState, useRef, useEffect } from 'react'
import type { ThemeId } from '../hooks/useTheme.ts'
import { THEMES, ACCENT_COLORS } from '../hooks/useTheme.ts'
import '../styles/theme-picker.css'

interface ThemePickerProps {
  theme: ThemeId
  resolvedTheme: string
  accentColor: string | null
  onThemeChange: (id: ThemeId) => void
  onAccentChange: (color: string | null) => void
}

export function ThemePicker({ theme, resolvedTheme, accentColor, onThemeChange, onAccentChange }: ThemePickerProps) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

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

  // Keyboard shortcut: Ctrl+Shift+T
  useEffect(() => {
    function handleKey(e: KeyboardEvent) {
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'T') {
        e.preventDefault()
        setOpen(prev => !prev)
      }
    }
    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [])

  const currentTheme = THEMES.find(t => t.id === theme)
  const icon = currentTheme?.icon ?? '⚙️'
  const isDark = ['dark', 'matrix', 'midnight'].includes(resolvedTheme)

  return (
    <div className="theme-picker-container" ref={ref}>
      <button
        className="theme-picker-trigger"
        onClick={() => setOpen(prev => !prev)}
        title="Switch theme (Ctrl+Shift+T)"
        aria-label="Switch theme"
        aria-expanded={open}
      >
        <span className="theme-picker-icon">{icon}</span>
      </button>

      {open && (
        <div className="theme-picker-dropdown" role="menu">
          <div className="theme-picker-section-label">Themes</div>

          {THEMES.map(t => (
            <button
              key={t.id}
              className={`theme-picker-item ${theme === t.id ? 'active' : ''}`}
              onClick={() => { onThemeChange(t.id); setOpen(false) }}
              role="menuitem"
            >
              <span className="theme-picker-item-icon">{t.icon}</span>
              <span className="theme-picker-item-label">{t.name}</span>
              {theme === t.id && <span className="theme-picker-check">✓</span>}
            </button>
          ))}

          <div className="theme-picker-separator" />

          <div className="theme-picker-section-label">Accent Color</div>
          <div className="theme-picker-accents">
            {ACCENT_COLORS.map(c => (
              <button
                key={c.name}
                className={`theme-picker-swatch ${accentColor === c.light || accentColor === c.dark ? 'active' : ''}`}
                style={{ backgroundColor: isDark ? c.dark : c.light }}
                onClick={() => {
                  const color = isDark ? c.dark : c.light
                  onAccentChange(accentColor === color ? null : color)
                }}
                title={c.name}
                aria-label={`Accent color: ${c.name}`}
              />
            ))}
          </div>

          <div className="theme-picker-separator" />

          <button
            className={`theme-picker-item ${theme === 'system' ? 'active' : ''}`}
            onClick={() => { onThemeChange('system'); setOpen(false) }}
            role="menuitem"
          >
            <span className="theme-picker-item-icon">⚙️</span>
            <span className="theme-picker-item-label">System (auto)</span>
            {theme === 'system' && <span className="theme-picker-check">✓</span>}
          </button>
        </div>
      )}
    </div>
  )
}
