import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, X } from 'lucide-react';
import { searchService } from '@/services/searchService';
export default function WorkshopSearch() {
  const [term, setTerm] = useState('');
  const [results, setResults] = useState([]);
  const [open, setOpen] = useState(false);
  const navigate = useNavigate();
  useEffect(() => { let alive = true; if (!term.trim()) { setResults([]); return; } const id = setTimeout(async () => { const r = await searchService.search(term); if (alive) { setResults(r); setOpen(true); } }, 250); return () => { alive = false; clearTimeout(id); }; }, [term]);
  const go = (r) => { setOpen(false); setTerm(''); navigate(r.to); };
  return <div className="relative px-3 pb-2">
    <div className="relative"><Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-500" /><input className="workshop-input mt-0 !min-h-9 pl-10 pr-8 text-sm" placeholder="Search workshop records…" value={term} onChange={(e) => setTerm(e.target.value)} onFocus={() => results.length && setOpen(true)} /><button className="absolute right-2 top-1.5 icon-btn !min-h-6 !min-w-6" aria-label="Clear search" onClick={() => { setTerm(''); setResults([]); setOpen(false); }}>{term && <X className="h-3.5 w-3.5" />}</button></div>
    {open && results.length > 0 && <div className="absolute z-50 mt-1 max-h-80 w-[calc(100%-1.5rem)] overflow-y-auto rounded-xl border border-shire-border bg-shire-panel shadow-2xl">{results.map((r, i) => <button key={i} onClick={() => go(r)} className="flex w-full items-center justify-between gap-2 border-b border-white/5 px-3 py-2 text-left text-sm hover:bg-shire-purple/10"><span><span className="font-medium text-violet-300">{r.label}</span><span className="ml-2 text-xs text-slate-500">{r.sub}</span></span><span className="text-xs text-slate-500">{r.type}</span></button>)}</div>}
    {open && term.trim() && results.length === 0 && <div className="absolute z-50 mt-1 w-[calc(100%-1.5rem)] rounded-xl border border-shire-border bg-shire-panel px-3 py-2 text-sm text-slate-500">No matching records.</div>}
  </div>;
}