import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Factory, Truck, CreditCard, XCircle, Archive, RotateCcw } 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 LoadingPanel from '@/components/workshop/LoadingPanel';
import { orderService } from '@/services/orderService';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { quoteService } from '@/services/quoteService';
import { manufacturingService } from '@/services/manufacturingService';
import { shipmentService } from '@/services/shipmentService';
import { auditService } from '@/services/auditService';
const PRODUCTION = ['Awaiting measurements','Ready for design','Awaiting approval','Ready for CAD','CAD in progress','Test print','Fit review','Final print','Post-processing','Inspection','Ready to ship','Shipped','Delivered','Complete'];
export default function OrderDetail() {
  const { orderId } = useParams();
  const [data, setData] = useState(null);
  const [busy, setBusy] = useState(false);
  const load = async () => {
    const order = await orderService.get(orderId);
    const [customer, project, quote, jobs, shipments, audits] = await Promise.all([
      order?.customer_uuid ? customerService.get(order.customer_uuid) : Promise.resolve(null),
      order?.project_uuid ? projectService.get(order.project_uuid) : Promise.resolve(null),
      order?.quote_uuid ? quoteService.get(order.quote_uuid) : Promise.resolve(null),
      manufacturingService.forOrder(orderId),
      shipmentService.forOrder(orderId),
      auditService.list(),
    ]);
    setData({ order, customer, project, quote, jobs, shipments, audits: (audits || []).filter((a) => a.record_uuid === orderId).sort((a, b) => (b.created_date || '').localeCompare(a.created_date || '')) });
  };
  useEffect(() => { load(); }, [orderId]);
  if (!data) return <LoadingPanel />;
  const { order, customer, project, quote, jobs, shipments, audits } = data;
  const audited = (fn) => async () => { setBusy(true); try { await fn(); await load(); } finally { setBusy(false); } };
  const recordPayment = audited(() => { const amt = prompt('Payment amount received (AUD):'); return amt && orderService.recordPayment(order.id, order.uuid, Number(amt), 'Ray'); });
  const createJob = audited(() => manufacturingService.create({ order_uuid: order.uuid, project_uuid: order.project_uuid, customer_uuid: order.customer_uuid, cover_revision: order.cover_revision, status: 'CAD required' }, 'Ray'));
  const prepareShip = audited(() => shipmentService.create({ order_uuid: order.uuid, customer_uuid: order.customer_uuid, recipient: customer?.full_name, address: customer?.shipping_address || customer?.address }, 'Ray'));
  const cancel = audited(() => { const reason = prompt('Reason for cancellation:'); return reason && orderService.cancel(order.id, order.uuid, reason, 'Ray'); });
  const setStatus = audited((s) => orderService.setStatus(order.id, order.uuid, s, 'Ray'));
  return <><Breadcrumbs items={[{ label: 'Orders', to: '/orders' }, { label: order.order_number }]} /><PageHeader eyebrow={order.order_number} title={customer?.full_name || 'Unknown customer'} description={`${project?.project_id || 'No project'} · Rev ${order.cover_revision || project?.revision || 1}`} action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to={`/customers/${order.customer_uuid}`}>Open Customer</Link><Link className="btn-secondary" to={`/projects/${order.project_uuid}`}>Open Project</Link><button disabled={busy} onClick={recordPayment} className="btn-secondary"><CreditCard />Record Payment</button><button disabled={busy} onClick={createJob} className="btn-secondary"><Factory />Create Manufacturing Job</button><button disabled={busy} onClick={prepareShip} className="btn-secondary"><Truck />Prepare Shipment</button><button disabled={busy} onClick={cancel} className="btn-secondary"><XCircle />Cancel with Reason</button></div>} /><div className="grid gap-5 lg:grid-cols-2"><section className="panel p-5"><h2 className="section-title">Customer & Contact</h2><FieldList rows={[['Customer number', customer?.customer_number], ['Email', customer?.email], ['Phone', customer?.phone], ['Billing contact', customer?.billing_contact], ['Shipping address', customer?.shipping_address || customer?.address], ['Preferred contact', customer?.preferred_contact_method]]} /></section><section className="panel p-5"><h2 className="section-title">Project</h2><FieldList rows={[['Project reference', <Link className="text-violet-300" to={`/projects/${order.project_uuid}`}>{project?.project_id}</Link>], ['Revision', order.cover_revision || project?.revision], ['Limb', project?.prosthesis_configuration], ['Prosthesis', project?.prosthesis_configuration], ['Due date', order.due_date]]} /></section><section className="panel p-5"><h2 className="section-title">Financial</h2><FieldList rows={[['Quote reference', quote?.quote_number], ['Quote amount', quote?.amount != null ? `$${quote.amount}` : null], ['Deposit paid', order.deposit ? `$${order.deposit}` : null], ['Balance', order.balance != null ? `$${order.balance}` : null], ['Payment status', <StatusPill tone={order.payment_status === 'Paid' ? 'green' : 'amber'}>{order.payment_status || 'Unpaid'}</StatusPill>], ['Funding method', order.funding_type], ['Funding approval', order.funding_approval_status], ['Approval reference', order.approval_reference], ['Invoice status', order.invoice_status]]} /><p className="mt-3 text-xs text-slate-500">Payment is only shown as paid when a real recorded payment exists. No payment is assumed.</p></section><section className="panel p-5"><h2 className="section-title">Production Status</h2><div className="flex flex-wrap items-center gap-2"><StatusPill tone="cyan">{order.production_status}</StatusPill><select disabled={busy} className="workshop-input mt-0 max-w-xs" value={order.production_status} onChange={(e) => setStatus(e.target.value)}>{PRODUCTION.map((p) => <option key={p}>{p}</option>)}</select></div>{order.cancel_reason && <p className="mt-3 rounded-lg bg-red-400/10 p-3 text-sm text-red-200">Cancelled: {order.cancel_reason}</p>}</section><section className="panel p-5"><h2 className="section-title">Manufacturing Jobs ({jobs.length})</h2>{jobs.length ? <div className="space-y-2">{jobs.map((j) => <Link key={j.uuid} to={`/manufacturing/${j.uuid}`} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2 text-sm hover:border-shire-purple/40"><span className="font-medium text-violet-300">{j.job_reference}</span><StatusPill tone="slate">{j.status}</StatusPill></Link>)}</div> : <p className="text-sm text-slate-500">No manufacturing jobs yet.</p>}</section><section className="panel p-5"><h2 className="section-title">Shipping ({shipments.length})</h2>{shipments.length ? shipments.map((s) => <div key={s.uuid} className="mb-2 rounded-lg border border-white/10 p-3 text-sm text-slate-300"><FieldList rows={[['Carrier', s.carrier], ['Tracking', s.tracking_number], ['Dispatched', s.dispatch_date], ['Delivered', s.delivered_date], ['Notes', s.notes]]} /></div>) : <p className="text-sm text-slate-500">No shipments prepared yet.</p>}</section><section className="panel p-5"><h2 className="section-title">Audit History</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}</span></li>)}</ol> : <p className="text-sm text-slate-500">No audit events recorded.</p>}</section></div><div className="mt-5">{order.record_state === 'archived' ? <button disabled={busy} onClick={audited(() => orderService.restore(order, 'Ray'))} className="btn-secondary"><RotateCcw />Restore order</button> : <button disabled={busy} onClick={audited(() => orderService.archive(order, 'Ray'))} className="btn-secondary"><Archive />Archive order</button>}</div></>;
}