import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Edit, PlusCircle, Ruler, Receipt, ShoppingCart, Archive, RotateCcw, Activity } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import Breadcrumbs from '@/components/workshop/Breadcrumbs';
import FieldList from '@/components/workshop/FieldList';
import StatusPill from '@/components/workshop/StatusPill';
import OriginBadge from '@/components/workshop/OriginBadge';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import CustomerForm from '@/components/customers/CustomerForm';
import LimbForm from '@/components/customers/LimbForm';
import ProsthesisForm from '@/components/customers/ProsthesisForm';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { quoteService } from '@/services/quoteService';
import { orderService } from '@/services/orderService';
import { completedCoverService } from '@/services/completedCoverService';
import { auditService } from '@/services/auditService';
import { adapters } from '@/services/serviceConfig';

const TABS = [['overview','Overview'],['limbs','Limb Profiles'],['prostheses','Prostheses & Components'],['measurements','Measurements'],['projects','Projects'],['quotes','Quotes'],['orders','Orders'],['covers','Completed Covers'],['history','History']];

export default function CustomerDetail() {
  const { uuid } = useParams();
  const [data, setData] = useState(null);
  const [tab, setTab] = useState('overview');
  const [mode, setMode] = useState('');
  const [busy, setBusy] = useState(false);
  const load = async () => {
    const customer = await customerService.get(uuid);
    if (!customer) { setData({ notFound: true }); return; }
    const history = await customerService.history(uuid);
    const [sessions, quotes, orders, covers, allAudits] = await Promise.all([
      adapters.database.filter('MeasurementSession', { customer_uuid: uuid }),
      quoteService.forCustomer(uuid),
      orderService.forCustomer(uuid),
      completedCoverService.forCustomer(uuid),
      auditService.list(),
    ]);
    const related = new Set([uuid, ...history.projects.map((p) => p.uuid), ...quotes.map((q) => q.uuid), ...orders.map((o) => o.uuid), ...covers.map((c) => c.uuid), ...sessions.map((s) => s.uuid)]);
    const audits = (allAudits || []).filter((a) => related.has(a.record_uuid)).sort((a, b) => (b.created_date || '').localeCompare(a.created_date || ''));
    setData({ customer, history, sessions, quotes, orders, covers, audits });
  };
  useEffect(() => { load(); }, [uuid]);
  if (!data) return <LoadingPanel />;
  if (data.notFound) return <div className="panel mx-auto mt-10 max-w-lg p-8 text-center"><h1 className="text-xl font-semibold text-white">Customer not found</h1><Link className="btn-secondary mt-4" to="/customers">Back to customers</Link></div>;
  const { customer, history, sessions, quotes, orders, covers, audits } = data;
  const act = (fn) => async () => { setBusy(true); try { await fn(); await load(); } finally { setBusy(false); } };
  const update = async (f) => { await customerService.update(customer.id, customer.uuid, f, 'Ray'); setMode(''); load(); };
  const addLimb = async (f) => { await customerService.createLimb({ ...f, customer_uuid: uuid, data_label: 'WORKSHOP RECORD' }, 'Ray'); setMode(''); load(); };
  const addProsthesis = async (f) => { await customerService.createProsthesis(f, 'Ray'); setMode(''); load(); };
  const firstProject = history.projects[0];
  const prepareQuote = act(() => firstProject ? quoteService.create({ project_uuid: firstProject.uuid, customer_uuid: uuid, amount: 0, funding_type: 'Quote-only' }, 'Ray') : null);
  const returning = history.projects.length > 0 || covers.length > 0;

  return <><Breadcrumbs items={[{ label: 'Customers', to: '/customers' }, { label: customer.full_name }]} /><PageHeader eyebrow={`${customer.customer_number} · ${customer.data_label}`} title={customer.full_name} description={`${customer.funding_method || 'Funding not selected'} · ${customer.approval_status || 'Approval not requested'}`} action={<div className="flex flex-wrap gap-2"><button className="btn-secondary" onClick={() => setMode('edit')}><Edit />Edit Customer</button><Link className="btn-primary" to="/new-cover"><PlusCircle />Start New Cover</Link><button className="btn-secondary" onClick={() => setMode('limb')}>Add Limb Profile</button><button className="btn-secondary" onClick={() => setMode('prosthesis')}>Add Prosthesis</button><Link className="btn-secondary" to="/measurements"><Ruler />Request Measurements</Link><button disabled={busy || !firstProject} onClick={prepareQuote} className="btn-secondary"><Receipt />Prepare Quote</button></div>} /><div className="mb-5 flex flex-wrap items-center gap-2"><StatusPill tone={customer.record_state === 'archived' ? 'slate' : 'green'}>{customer.record_state === 'archived' ? 'Archived' : 'Active'}</StatusPill>{returning && <StatusPill tone="cyan">Returning customer</StatusPill>}<OriginBadge record={customer} showAll /></div>

  {mode === 'edit' && <div className="panel mb-5 p-6"><CustomerForm initial={customer} onSave={update} onCancel={() => setMode('')} /></div>}
  {mode === 'limb' && <div className="panel mb-5 p-6"><LimbForm customerUuid={uuid} onSave={addLimb} onCancel={() => setMode('')} /></div>}
  {mode === 'prosthesis' && <div className="panel mb-5 p-6"><ProsthesisForm customerUuid={uuid} limbs={history.limbs} onSave={addProsthesis} onCancel={() => setMode('')} /></div>}

  <div className="mb-4 flex flex-wrap gap-1.5">{TABS.map(([id, label]) => <button key={id} onClick={() => setTab(id)} className={`rounded-lg px-3 py-1.5 text-sm font-medium transition ${tab === id ? 'bg-shire-purple text-white' : 'border border-shire-border text-slate-400 hover:text-shire-purple-bright'}`}>{label}</button>)}</div>

  {tab === 'overview' && <div className="grid gap-5 lg:grid-cols-2"><section className="panel p-5"><h2 className="section-title">Customer Overview</h2><FieldList rows={[['Customer number', customer.customer_number], ['Full name', customer.full_name], ['Preferred name', customer.preferred_name], ['Date of birth', customer.date_of_birth], ['Email', customer.email], ['Phone', customer.phone], ['Pronouns', customer.pronouns], ['Billing address', customer.address], ['Shipping address', customer.shipping_address], ['Preferred contact', customer.preferred_contact_method], ['Emergency contact', customer.emergency_contact]]} /></section><section className="panel p-5"><h2 className="section-title">Funding</h2><FieldList rows={[['Funding method', customer.funding_method], ['NDIS number', customer.ndis_number], ['Plan dates', customer.plan_dates], ['Plan manager', customer.plan_manager_name], ['Plan manager email', customer.plan_manager_email], ['Plan manager phone', customer.plan_manager_phone], ['Billing contact', customer.billing_contact], ['Purchase order', customer.purchase_order_number], ['Invoice notes', customer.invoice_notes], ['Approval status', customer.approval_status]]} /></section><section className="panel p-5"><h2 className="section-title">Record</h2><FieldList rows={[['Created date', customer.created_date?.slice(0, 10)], ['Last activity', customer.updated_date?.slice(0, 10)], ['Internal notes', customer.internal_notes], ['Data origin', customer.data_origin], ['Returning customer', returning ? 'Yes' : 'No']]} />{customer.record_state === 'archived' ? <button disabled={busy} onClick={act(() => customerService.restore(customer, 'Ray'))} className="btn-secondary mt-4"><RotateCcw />Restore customer</button> : <button disabled={busy} onClick={act(() => customerService.archive(customer, 'Ray'))} className="btn-secondary mt-4"><Archive />Archive customer</button>}</section></div>}

  {tab === 'limbs' && <section className="panel p-5"><h2 className="section-title">Limb Profiles ({history.limbs.length})</h2>{history.limbs.length ? <div className="space-y-2">{history.limbs.map((l) => <div key={l.uuid} className="rounded-lg border border-white/10 p-3"><div className="flex items-center justify-between"><span className="font-medium text-white">{l.profile_name}</span><StatusPill tone="cyan">{l.configuration}</StatusPill></div><dl className="mt-2 grid grid-cols-2 gap-x-4 gap-y-1 text-sm text-slate-400"><dt className="text-slate-500">Interface</dt><dd>{l.interface_type}</dd><dt className="text-slate-500">Manufacturer / model</dt><dd>{l.prosthesis_manufacturer} {l.prosthesis_model}</dd><dt className="text-slate-500">Fitting date</dt><dd>{l.fitting_date}</dd><dt className="text-slate-500">Related covers</dt><dd>{history.projects.filter((p) => p.limb_profile_uuid === l.uuid).length}</dd></dl></div>)}</div> : <p className="text-sm text-slate-500">No limb profiles recorded.</p>}</section>}

  {tab === 'prostheses' && <section className="panel p-5"><h2 className="section-title">Prostheses ({history.prostheses.length})</h2>{history.prostheses.length ? <div className="space-y-2">{history.prostheses.map((p) => <div key={p.uuid} className="rounded-lg border border-white/10 p-3"><div className="flex items-center justify-between"><span className="font-medium text-white">{p.name}</span><StatusPill tone={p.status === 'active' ? 'green' : 'slate'}>{p.status}</StatusPill></div><dl className="mt-2 grid grid-cols-2 gap-x-4 gap-y-1 text-sm text-slate-400"><dt className="text-slate-500">Manufacturer / model</dt><dd>{p.manufacturer} {p.model}</dd><dt className="text-slate-500">Serial</dt><dd>{p.serial_number}</dd><dt className="text-slate-500">Configuration</dt><dd>{p.configuration}</dd><dt className="text-slate-500">Fitting date</dt><dd>{p.fitting_date}</dd></dl></div>)}</div> : <p className="text-sm text-slate-500">No prostheses recorded.</p>}</section>}

  {tab === 'measurements' && <section className="panel p-5"><h2 className="section-title">Measurement Sessions ({sessions.length})</h2>{sessions.length ? <div className="space-y-2">{sessions.map((s) => <Link key={s.uuid} to={`/measurements/${s.uuid}`} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm hover:border-shire-purple/40"><div><span className="font-medium text-violet-300">{s.workflow}</span><span className="ml-2 text-xs text-slate-500">{s.measured_date} · {s.measured_by}</span></div><div className="flex items-center gap-2"><StatusPill tone={s.status === 'Complete' ? 'green' : 'amber'}>{s.status}</StatusPill><span className="text-xs text-slate-500">{s.progress_percent || 0}%</span></div></Link>)}</div> : <p className="text-sm text-slate-500">No measurement sessions recorded.</p>}</section>}

  {tab === 'projects' && <section className="panel p-5"><h2 className="section-title">Cover Projects ({history.projects.length})</h2>{history.projects.length ? <div className="space-y-2">{history.projects.map((p) => <Link key={p.uuid} to={`/projects/${p.uuid}`} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm hover:border-shire-purple/40"><div><span className="font-medium text-violet-300">{p.project_id}</span><span className="ml-2 text-xs text-slate-500">Rev {p.revision}</span></div><StatusPill tone={p.status === 'Complete' ? 'green' : 'amber'}>{p.status}</StatusPill></Link>)}</div> : <p className="text-sm text-slate-500">No cover projects yet.</p>}</section>}

  {tab === 'quotes' && <section className="panel p-5"><h2 className="section-title">Quotes ({quotes.length})</h2>{quotes.length ? <div className="space-y-2">{quotes.map((q) => <div key={q.uuid} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm"><div><span className="font-medium text-violet-300">{q.quote_number}</span><span className="ml-2 text-xs text-slate-500">{q.sent_date}</span></div><StatusPill tone={q.approval_status === 'Approved' ? 'green' : 'amber'}>{q.approval_status}</StatusPill></div>)}</div> : <p className="text-sm text-slate-500">No quotes yet.</p>}</section>}

  {tab === 'orders' && <section className="panel p-5"><h2 className="section-title">Orders ({orders.length})</h2>{orders.length ? <div className="space-y-2">{orders.map((o) => <Link key={o.uuid} to={`/orders/${o.uuid}`} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm hover:border-shire-purple/40"><div><span className="font-medium text-violet-300">{o.order_number}</span><span className="ml-2 text-xs text-slate-500">{o.order_date}</span></div><StatusPill tone={o.production_status === 'Complete' ? 'green' : 'amber'}>{o.production_status}</StatusPill></Link>)}</div> : <p className="text-sm text-slate-500">No orders yet.</p>}</section>}

  {tab === 'covers' && <section className="panel p-5"><h2 className="section-title">Completed Covers ({covers.length})</h2>{covers.length ? <div className="space-y-2">{covers.map((c) => <Link key={c.uuid} to={`/completed-covers/${c.uuid}`} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm hover:border-shire-purple/40"><div><span className="font-medium text-violet-300">{c.cover_reference}</span><span className="ml-2 text-xs text-slate-500">{c.design_name}</span></div><StatusPill tone={c.inspection_result === 'Passed' ? 'green' : 'amber'}>{c.inspection_result || 'Pending'}</StatusPill></Link>)}</div> : <p className="text-sm text-slate-500">No completed covers yet.</p>}</section>}

  {tab === 'history' && <section className="panel p-5"><h2 className="section-title"><Activity className="inline h-4 w-4" /> Audit Timeline</h2>{audits.length ? <ol className="space-y-2 text-sm text-slate-400">{audits.map((a) => <li key={a.uuid} className="border-l-2 border-shire-purple/30 pl-3"><span className="text-slate-200">{a.summary}</span><span className="ml-2 text-xs text-slate-600">{a.actor_name} · {a.created_date?.slice(0, 10)}</span></li>)}</ol> : <p className="text-sm text-slate-500">No audit events recorded.</p>}</section>}
  </>;
}