import { useEffect, useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import ManufacturingJobCard from '@/components/manufacturing/ManufacturingJobCard';
import HideFictionalToggle from '@/components/workshop/HideFictionalToggle';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { manufacturingService } from '@/services/manufacturingService';
import { orderService } from '@/services/orderService';
import { projectService } from '@/services/projectService';
import { workshopService } from '@/services/workshopService';
const FILTERS = ['All', 'Waiting', 'CAD required', 'Ready to print', 'Printing', 'Post-processing', 'Inspection', 'Passed', 'Failed', 'Complete', 'Archived'];
export default function Manufacturing() {
  const [jobs, setJobs] = useState(null);
  const [orders, setOrders] = useState([]);
  const [projects, setProjects] = useState([]);
  const [filter, setFilter] = useState('All');
  const [hideFictional, setHideFictional] = useState(true);
  const [search, setSearch] = useState('');
  const load = () => { Promise.all([manufacturingService.list(), orderService.list(), projectService.list()]).then(([j, o, p]) => { setJobs(j); setOrders(o); setProjects(p); }); };
  useEffect(() => { load(); }, []);
  const ord = (uuid) => orders.find((o) => o.uuid === uuid);
  const proj = (uuid) => projects.find((p) => p.uuid === uuid);
  const shown = useMemo(() => {
    if (!jobs) return [];
    let list = hideFictional ? workshopService.hideFictional(jobs) : jobs;
    if (filter === 'Archived') list = list.filter((j) => j.record_state === 'archived');
    else if (filter !== 'All') list = list.filter((j) => j.status === filter);
    if (search.trim()) { const t = search.toLowerCase(); list = list.filter((j) => (j.job_reference || '').toLowerCase().includes(t) || (proj(j.project_uuid)?.project_id || '').toLowerCase().includes(t) || (ord(j.order_uuid)?.order_number || '').toLowerCase().includes(t)); }
    return list;
  }, [jobs, filter, hideFictional, search, orders, projects]);
  const toggle = async (j) => { j.record_state === 'archived' ? await manufacturingService.restore(j, 'Ray') : await manufacturingService.archive(j, 'Ray'); load(); };
  if (!jobs) return <LoadingPanel />;
  return <><PageHeader eyebrow="Production jobs" title="Manufacturing" description="Every print and finishing job, linked to its order, project and completed cover." /><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 jobs…" value={search} onChange={(e) => setSearch(e.target.value)} /></label><select className="workshop-input mt-0 max-w-xs" value={filter} onChange={(e) => setFilter(e.target.value)}>{FILTERS.map((f) => <option key={f}>{f}</option>)}</select><HideFictionalToggle value={hideFictional} onChange={setHideFictional} /></div><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{shown.map((j) => <ManufacturingJobCard key={j.uuid} job={j} order={ord(j.order_uuid)} project={proj(j.project_uuid)} onToggle={toggle} />)}</div>{shown.length === 0 && <p className="mt-8 text-center text-sm text-slate-500">No manufacturing jobs match the current filter.</p>}</>;
}