import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Palette, Check } from 'lucide-react';
import { useTheme, type Theme } from '../lib/theme';

const THEME_LABELS: Record<Theme, string> = {
  skeen: 'SKEEN',
  homenest: 'HomeNest',
  clasico: 'Clásico',
};

interface ThemePickerProps {
  triggerClassName?: string;
}

export const ThemePicker: FC<ThemePickerProps> = ({ triggerClassName }) => {
  const { theme, setTheme } = useTheme();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        title="Cambiar tema"
        className={
          triggerClassName ||
          'hidden sm:inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-full text-xs font-medium transition border border-theme-border bg-theme-surface text-theme-heading hover:bg-theme-accent-bg'
        }
      >
        <Palette size={14} />
        {THEME_LABELS[theme]}
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-2 z-50 w-44 rounded-2xl border border-theme-border bg-theme-surface shadow-card p-1.5">
          <p className="px-2.5 py-1.5 text-[10px] uppercase tracking-wider text-theme-muted font-medium">
            Tema
          </p>
          {(Object.keys(THEME_LABELS) as Theme[]).map((t) => {
            const selected = theme === t;
            return (
              <button
                key={t}
                type="button"
                onClick={() => { setTheme(t); setOpen(false); }}
                className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm transition-colors ${
                  selected ? 'bg-theme-accent-bg text-theme-heading font-medium' : 'text-theme-muted hover:bg-theme-bg hover:text-theme-heading'
                }`}
              >
                {THEME_LABELS[t]}
                {selected && <Check size={14} className="ml-auto" />}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default ThemePicker;
