import { useEffect, useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import CompletedCoverCard from '@/components/covers/CompletedCoverCard';
import HideFictionalToggle from '@/components/workshop/HideFictionalToggle';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { completedCoverService } from '@/services/completedCoverService';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { workshopService } from '@/services/workshopService';
export default function CompletedCovers() {
  const [covers, setCovers] = useState(null);
  const [customers, setCustomers] = useState([]);
  const [projects, setProjects] = useState([]);
  const [hideFictional, setHideFictional] = useState(true);
  const [search, setSearch] = useState('');
  const [material, setMaterial] = useState('All');
  const [delivered, setDelivered] = useState('All');
  const load = () => { Promise.all([completedCoverService.list(), customerService.list(), projectService.list()]).then(([c, cu, p]) => { setCovers(c); setCustomers(cu); setProjects(p); }); };
  useEffect(() => { load(); }, []);
  const cust = (uuid) => customers.find((c) => c.uuid === uuid);
  const proj = (uuid) => projects.find((p) => p.uuid === uuid);
  const materials = useMemo(() => ['All', ...new Set((covers || []).map((c) => c.material).filter(Boolean))], [covers]);
  const shown = useMemo(() => {
    if (!covers) return [];
    let list = hideFictional ? workshopService.hideFictional(covers) : covers;
    if (material !== 'All') list = list.filter((c) => c.material === material);
    if (delivered === 'Delivered') list = list.filter((c) => c.delivery_date);
    else if (delivered === 'Awaiting delivery') list = list.filter((c) => !c.delivery_date);
    if (search.trim()) { const t = search.toLowerCase(); list = list.filter((c) => (c.cover_reference || '').toLowerCase().includes(t) || (c.design_name || '').toLowerCase().includes(t) || (cust(c.customer_uuid)?.full_name || '').toLowerCase().includes(t) || (proj(c.project_uuid)?.project_id || '').toLowerCase().includes(t)); }
    return list;
  }, [covers, hideFictional, material, delivered, search, customers, projects]);
  const toggle = async (c) => { c.record_state === 'archived' ? await completedCoverService.restore(c, 'Ray') : await completedCoverService.archive(c, 'Ray'); load(); };
  if (!covers) return <LoadingPanel />;
  return <><PageHeader eyebrow="Manufactured cover library" title="Completed Covers" description="Every SHiRE prosthetic cover produced, with design, material, inspection and delivery records." /><div className="mb-5 flex flex-wrap items-center gap-2"><label className="relative block"><Search className="absolute left-3 top-3 h-4 w-4 text-slate-500" /><input className="workshop-input mt-0 pl-10" placeholder="Search covers…" value={search} onChange={(e) => setSearch(e.target.value)} /></label><select className="workshop-input mt-0 max-w-xs" value={material} onChange={(e) => setMaterial(e.target.value)}>{materials.map((m) => <option key={m}>{m}</option>)}</select><select className="workshop-input mt-0 max-w-xs" value={delivered} onChange={(e) => setDelivered(e.target.value)}><option>All</option><option>Delivered</option><option>Awaiting delivery</option></select><HideFictionalToggle value={hideFictional} onChange={setHideFictional} /></div><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{shown.map((c) => <CompletedCoverCard key={c.uuid} cover={c} customer={cust(c.customer_uuid)} project={proj(c.project_uuid)} onToggle={toggle} />)}</div>{shown.length === 0 && <p className="mt-8 text-center text-sm text-slate-500">No completed covers match the current filter.</p>}</>;
}