import { useEffect, useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import { Link } from 'react-router-dom';
import PageHeader from '@/components/workshop/PageHeader';
import StatusPill from '@/components/workshop/StatusPill';
import OriginBadge from '@/components/workshop/OriginBadge';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { projectService } from '@/services/projectService';
import { customerService } from '@/services/customerService';
export default function IntakeRequests() {
  const [projects, setProjects] = useState(null);
  const [customers, setCustomers] = useState([]);
  const [search, setSearch] = useState('');
  useEffect(() => { Promise.all([projectService.list(), customerService.list()]).then(([p, c]) => { setProjects(p); setCustomers(c); }); }, []);
  const cust = (uuid) => customers.find((c) => c.uuid === uuid);
  const shown = useMemo(() => {
    if (!projects) return [];
    let list = projects.filter((p) => p.data_origin === 'Public Intake' || /intake/i.test(p.reason_for_cover || '') || /intake/i.test(p.measurement_method || ''));
    if (search.trim()) { const t = search.toLowerCase(); list = list.filter((p) => (p.project_id || '').toLowerCase().includes(t) || (cust(p.customer_uuid)?.full_name || '').toLowerCase().includes(t)); }
    return list;
  }, [projects, search, customers]);
  if (!projects) return <LoadingPanel />;
  return <><PageHeader eyebrow="Public submissions" title="Intake Requests" description="Cover requests submitted through the public design-your-cover form. Each links to the full project record." /><div className="mb-5"><label className="relative block max-w-md"><Search className="absolute left-3 top-3 h-4 w-4 text-slate-500" /><input className="workshop-input mt-0 pl-10" placeholder="Search intake reference or customer" value={search} onChange={(e) => setSearch(e.target.value)} /></label></div><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{shown.map((p) => <Link key={p.uuid} to={`/projects/${p.uuid}`} className="panel block p-5 transition hover:border-shire-purple/40"><div className="flex items-start justify-between gap-3"><div><p className="text-xs font-semibold text-violet-400">{p.project_id} · Rev {p.revision}</p><h2 className="mt-1 font-semibold text-white">{cust(p.customer_uuid)?.full_name || 'Unknown'}</h2></div><div className="flex flex-col items-end gap-1"><StatusPill tone="green">Public Intake</StatusPill><OriginBadge record={p} /></div></div><p className="mt-3 line-clamp-2 text-sm text-slate-400">{p.reason_for_cover}</p><span className="mt-4 inline-block btn-secondary text-sm">Open project</span></Link>)}</div>{shown.length === 0 && <p className="mt-8 text-center text-sm text-slate-500">No public intake requests found.</p>}</>;
}