import { useEffect, useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import OrderCard from '@/components/orders/OrderCard';
import HideFictionalToggle from '@/components/workshop/HideFictionalToggle';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { orderService } from '@/services/orderService';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { workshopService } from '@/services/workshopService';
const FILTERS = ['All', 'Awaiting measurements', 'Awaiting NDIS/plan-manager approval', 'Ready for CAD', 'In manufacturing', 'Awaiting inspection', 'Ready to ship', 'Shipped', 'Delivered', 'Complete', 'Cancelled', 'Archived'];
export default function Orders() {
  const [orders, setOrders] = useState(null);
  const [customers, setCustomers] = useState([]);
  const [projects, setProjects] = useState([]);
  const [filter, setFilter] = useState('All');
  const [hideFictional, setHideFictional] = useState(true);
  const [search, setSearch] = useState('');
  const load = () => { Promise.all([orderService.list(), customerService.list(), projectService.list()]).then(([o, c, p]) => { setOrders(o); setCustomers(c); setProjects(p); }); };
  useEffect(() => { load(); }, []);
  const cust = (uuid) => customers.find((c) => c.uuid === uuid);
  const proj = (uuid) => projects.find((p) => p.uuid === uuid);
  const shown = useMemo(() => {
    if (!orders) return [];
    let list = orders;
    if (hideFictional) list = workshopService.hideFictional(list);
    if (filter === 'Cancelled') list = list.filter((o) => o.cancel_reason || o.record_state === 'archived');
    else if (filter === 'Archived') list = list.filter((o) => o.record_state === 'archived');
    else if (filter === 'In manufacturing') list = list.filter((o) => ['CAD in progress', 'Test print', 'Final print', 'Post-processing'].includes(o.production_status));
    else if (filter !== 'All') list = list.filter((o) => o.production_status === filter || o.funding_approval_status === filter || o.shipping_status === filter);
    if (search.trim()) { const t = search.toLowerCase(); list = list.filter((o) => (o.order_number || '').toLowerCase().includes(t) || (cust(o.customer_uuid)?.full_name || '').toLowerCase().includes(t) || (proj(o.project_uuid)?.project_id || '').toLowerCase().includes(t)); }
    return list;
  }, [orders, filter, hideFictional, search, customers, projects]);
  const toggle = async (o) => { o.record_state === 'archived' ? await orderService.restore(o, 'Ray') : await orderService.archive(o, 'Ray'); load(); };
  if (!orders) return <LoadingPanel />;
  return <><PageHeader eyebrow="Production register" title="Orders" description="Every linked order, from intake approval through production, shipping and delivery." /><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 orders…" 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((o) => <OrderCard key={o.uuid} order={o} customer={cust(o.customer_uuid)} project={proj(o.project_uuid)} onToggle={toggle} />)}</div>{shown.length === 0 && <p className="mt-8 text-center text-sm text-slate-500">No orders match the current filter.</p>}</>;
}