import { useEffect, useMemo, useRef, useState } from 'react';
import type { UatStats, YearFilter } from './types';
import { diacritic, formatRON } from './utils';

interface Action {
  id: string;
  label: string;
  hint?: string;
  group: 'filtre' | 'localități' | 'navigare';
  perform: () => void;
}

interface Props {
  open: boolean;
  onClose: () => void;
  uats: UatStats[];
  year: YearFilter;
  onYearChange: (year: YearFilter) => void;
  onUatJump: (siruta: string) => void;
}

const YEARS: YearFilter[] = ['all', 2026, 2025, 2024, 2023, 2022, 2021, 2020];

export function CommandPalette({ open, onClose, uats, year, onYearChange, onUatJump }: Props) {
  const [q, setQ] = useState('');
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (open) {
      setQ('');
      setActiveIdx(0);
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [open]);

  // Esc closes globally
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        onClose();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open, onClose]);

  const actions: Action[] = useMemo(() => {
    const list: Action[] = [];

    // Year filter actions
    for (const y of YEARS) {
      if (y === year) continue;
      list.push({
        id: `year-${y}`,
        label: y === 'all' ? 'Filtrează: toți anii' : `Filtrează: anul ${y}`,
        hint: 'an',
        group: 'filtre',
        perform: () => {
          onYearChange(y);
          onClose();
        },
      });
    }

    // UAT search (top 200 by value to keep render cheap)
    const sorted = [...uats]
      .sort((a, b) => Number(b.total_value) - Number(a.total_value))
      .slice(0, 200);
    for (const u of sorted) {
      list.push({
        id: `uat-${u.siruta}`,
        label: u.uat_name,
        hint: `${u.county} · ${formatRON(Number(u.total_value))} RON`,
        group: 'localități',
        perform: () => {
          onUatJump(u.siruta);
          onClose();
        },
      });
    }

    // Navigate actions
    list.push({
      id: 'go-home',
      label: 'Du-te la pagina principală',
      hint: '/',
      group: 'navigare',
      perform: () => { window.location.href = '/'; },
    });
    list.push({
      id: 'go-produse',
      label: 'Du-te la produse',
      hint: '/produse',
      group: 'navigare',
      perform: () => { window.location.href = '/produse'; },
    });

    return list;
  }, [uats, year, onYearChange, onUatJump, onClose]);

  const filtered = useMemo(() => {
    const needle = diacritic(q.trim());
    if (!needle) return actions.slice(0, 50);
    return actions
      .filter((a) => diacritic(a.label).includes(needle) || (a.hint && diacritic(a.hint).includes(needle)))
      .slice(0, 50);
  }, [actions, q]);

  // Keep activeIdx in bounds
  useEffect(() => {
    if (activeIdx >= filtered.length) setActiveIdx(0);
  }, [filtered.length, activeIdx]);

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIdx((i) => Math.min(i + 1, filtered.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIdx((i) => Math.max(i - 1, 0));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      filtered[activeIdx]?.perform();
    }
  };

  if (!open) return null;

  // Group filtered by group
  const grouped = filtered.reduce((acc, a) => {
    (acc[a.group] = acc[a.group] || []).push(a);
    return acc;
  }, {} as Record<Action['group'], Action[]>);

  let runningIdx = 0;

  return (
    <div className="harta-cmdk-backdrop" onClick={onClose}>
      <div className="harta-cmdk" onClick={(e) => e.stopPropagation()}>
        <div className="harta-cmdk-input-wrap">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-neutral-400 shrink-0">
            <circle cx="11" cy="11" r="8" />
            <line x1="21" y1="21" x2="16.65" y2="16.65" />
          </svg>
          <input
            ref={inputRef}
            type="text"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={onKeyDown}
            placeholder="Caută o localitate, filtrează după an..."
            className="harta-cmdk-input"
          />
          <kbd className="harta-cmdk-esc">esc</kbd>
        </div>

        <div className="harta-cmdk-results">
          {filtered.length === 0 ? (
            <div className="harta-cmdk-empty">Niciun rezultat pentru „{q}"</div>
          ) : (
            (['filtre', 'localități', 'navigare'] as const).map((g) => {
              const items = grouped[g];
              if (!items || items.length === 0) return null;
              return (
                <div key={g} className="harta-cmdk-group">
                  <div className="harta-cmdk-group-label">{g}</div>
                  {items.map((a) => {
                    const idx = runningIdx++;
                    return (
                      <button
                        key={a.id}
                        onClick={() => a.perform()}
                        onMouseEnter={() => setActiveIdx(idx)}
                        className={`harta-cmdk-item ${idx === activeIdx ? 'is-active' : ''}`}
                      >
                        <span className="flex-1 truncate">{a.label}</span>
                        {a.hint && <span className="harta-cmdk-hint">{a.hint}</span>}
                      </button>
                    );
                  })}
                </div>
              );
            })
          )}
        </div>

        <div className="harta-cmdk-footer">
          <span><kbd>↑</kbd><kbd>↓</kbd> navighează</span>
          <span><kbd>↵</kbd> selectează</span>
          <span><kbd>esc</kbd> închide</span>
        </div>
      </div>
    </div>
  );
}
