import { useEffect, useMemo, useState } from 'react';
import { Plus, Search } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import CustomerCard from '@/components/customers/CustomerCard';
import CustomerForm from '@/components/customers/CustomerForm';
import HideFictionalToggle from '@/components/workshop/HideFictionalToggle';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { orderService } from '@/services/orderService';
import { completedCoverService } from '@/services/completedCoverService';
import { adapters } from '@/services/serviceConfig';
import { workshopService } from '@/services/workshopService';
const FILTERS = ['All', 'New customers', 'Returning customers', 'Active projects', 'Awaiting measurements', 'Awaiting quote', 'Current orders', 'Completed customers', 'Archived'];
const SORTS = ['Recent activity', 'Name (A–Z)', 'Customer number'];
export default function Customers() {
  const [items, setItems] = useState([]);
  const [limbs, setLimbs] = useState([]);
  const [projects, setProjects] = useState([]);
  const [orders, setOrders] = useState([]);
  const [covers, setCovers] = useState([]);
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState('All');
  const [sort, setSort] = useState('Recent activity');
  const [hideFictional, setHideFictional] = useState(true);
  const [show, setShow] = useState(false);
  const load = () => { Promise.all([customerService.list(), adapters.database.list('LimbProfile'), projectService.list(), orderService.list(), completedCoverService.list()]).then(([c, l, p, o, cv]) => { setItems(c); setLimbs(l); setProjects(p); setOrders(o); setCovers(cv); }); };
  useEffect(() => { load(); }, []);
  const counts = useMemo(() => {
    const m = {};
    items.forEach((c) => { m[c.uuid] = { limbs: limbs.filter((l) => l.customer_uuid === c.uuid).length, projects: projects.filter((p) => p.customer_uuid === c.uuid).length, orders: orders.filter((o) => o.customer_uuid === c.uuid).length, covers: covers.filter((cv) => cv.customer_uuid === c.uuid).length }; });
    return m;
  }, [items, limbs, projects, orders, covers]);
  const filtered = useMemo(() => {
    let list = hideFictional ? workshopService.hideFictional(items) : items;
    if (filter === 'Archived') list = list.filter((c) => c.record_state === 'archived');
    else if (filter === 'New customers') list = list.filter((c) => (counts[c.uuid]?.projects || 0) === 0 && (counts[c.uuid]?.covers || 0) === 0);
    else if (filter === 'Returning customers') list = list.filter((c) => (counts[c.uuid]?.projects || 0) > 0 || (counts[c.uuid]?.covers || 0) > 0);
    else if (filter === 'Active projects') list = list.filter((c) => projects.some((p) => p.customer_uuid === c.uuid && p.status !== 'Complete' && p.record_state !== 'archived'));
    else if (filter === 'Awaiting measurements') list = list.filter((c) => projects.some((p) => p.customer_uuid === c.uuid && p.status === 'Awaiting measurements'));
    else if (filter === 'Awaiting quote') list = list.filter((c) => projects.some((p) => p.customer_uuid === c.uuid && (p.status === 'Awaiting workshop review' || p.status === 'Ready for design')));
    else if (filter === 'Current orders') list = list.filter((c) => orders.some((o) => o.customer_uuid === c.uuid && o.production_status !== 'Complete' && !o.cancel_reason));
    else if (filter === 'Completed customers') list = list.filter((c) => (counts[c.uuid]?.covers || 0) > 0);
    if (search.trim()) { const t = search.toLowerCase(); list = list.filter((c) => [c.full_name, c.preferred_name, c.email, c.phone, c.customer_number].join(' ').toLowerCase().includes(t)); }
    list = [...list].sort((a, b) => { if (sort === 'Name (A–Z)') return (a.full_name || '').localeCompare(b.full_name || ''); if (sort === 'Customer number') return (a.customer_number || '').localeCompare(b.customer_number || ''); return (b.updated_date || '').localeCompare(a.updated_date || ''); });
    return list;
  }, [items, filter, hideFictional, search, sort, counts, projects, orders]);
  const save = async (f) => { await customerService.create(f, 'Ray'); setShow(false); load(); };
  const toggle = async (c) => { c.record_state === 'archived' ? await customerService.restore(c, 'Ray') : await customerService.archive(c, 'Ray'); load(); };
  return <><PageHeader eyebrow="Returning-customer records" title="Customers" description="Search and inspect every customer with their full project, measurement, order and cover history." action={<button onClick={() => setShow(true)} className="btn-primary"><Plus />New customer</button>} />{show && <div className="panel mb-6 p-6"><CustomerForm onSave={save} onCancel={() => setShow(false)} /></div>}<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 name, email, phone or customer number" 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><select className="workshop-input mt-0 max-w-xs" value={sort} onChange={(e) => setSort(e.target.value)}>{SORTS.map((s) => <option key={s}>{s}</option>)}</select><HideFictionalToggle value={hideFictional} onChange={setHideFictional} /></div><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{filtered.map((c) => <CustomerCard key={c.uuid} customer={c} counts={counts[c.uuid]} onToggle={toggle} />)}</div>{filtered.length === 0 && <p className="mt-8 text-center text-sm text-slate-500">No customers match the current filter.</p>}</>;
}