import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { 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 OriginBadge from '@/components/workshop/OriginBadge';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { manufacturingService } from '@/services/manufacturingService';
import { orderService } from '@/services/orderService';
import { projectService } from '@/services/projectService';
import { customerService } from '@/services/customerService';
import { auditService } from '@/services/auditService';
const STATUSES = ['Waiting','CAD required','Ready to slice','Ready to print','Printing','Print failed','Reprint required','Post-processing','Inspection','Passed','Failed','Complete'];
export default function ManufacturingJobDetail() {
  const { jobId } = useParams();
  const [data, setData] = useState(null);
  const [busy, setBusy] = useState(false);
  const load = async () => {
    const job = await manufacturingService.get(jobId);
    const [order, project, customer, audits] = await Promise.all([
      job?.order_uuid ? orderService.get(job.order_uuid) : Promise.resolve(null),
      job?.project_uuid ? projectService.get(job.project_uuid) : Promise.resolve(null),
      job?.customer_uuid ? customerService.get(job.customer_uuid) : Promise.resolve(null),
      auditService.list(),
    ]);
    setData({ job, order, project, customer, audits: (audits || []).filter((a) => a.record_uuid === jobId).sort((a, b) => (b.created_date || '').localeCompare(a.created_date || '')) });
  };
  useEffect(() => { load(); }, [jobId]);
  if (!data) return <LoadingPanel />;
  const { job, order, project, customer, audits } = data;
  const audited = (fn) => async () => { setBusy(true); try { await fn(); await load(); } finally { setBusy(false); } };
  const setStatus = (s) => audited(() => manufacturingService.setStatus(job.id, job.uuid, s, 'Ray'))();
  const tone = job.status === 'Complete' || job.status === 'Passed' ? 'green' : job.status === 'Print failed' || job.status === 'Failed' || job.status === 'Reprint required' ? 'red' : 'amber';
  return <><Breadcrumbs items={[{ label: 'Manufacturing', to: '/manufacturing' }, { label: job.job_reference }]} /><PageHeader eyebrow={job.job_reference} title={project?.project_id || 'Manufacturing job'} description={`${order?.order_number || 'No order linked'} · ${customer?.full_name || 'Unknown customer'}`} action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to={`/orders/${job.order_uuid}`}>Open Order</Link><Link className="btn-secondary" to={`/projects/${job.project_uuid}`}>Open Project</Link>{job.completed_cover_uuid && <Link className="btn-secondary" to={`/completed-covers/${job.completed_cover_uuid}`}>Open Completed Cover</Link>}</div>} /><div className="mb-5"><OriginBadge record={job} showAll /></div><div className="grid gap-5 lg:grid-cols-2"><section className="panel p-5"><h2 className="section-title">Status</h2><div className="flex flex-wrap items-center gap-2"><StatusPill tone={tone}>{job.status}</StatusPill><select disabled={busy} className="workshop-input mt-0 max-w-xs" value={job.status} onChange={(e) => setStatus(e.target.value)}>{STATUSES.map((s) => <option key={s}>{s}</option>)}</select></div></section><section className="panel p-5"><h2 className="section-title">Links</h2><FieldList rows={[['Order', <Link className="text-violet-300" to={`/orders/${job.order_uuid}`}>{order?.order_number}</Link>], ['Project', <Link className="text-violet-300" to={`/projects/${job.project_uuid}`}>{project?.project_id}</Link>], ['Cover revision', job.cover_revision], ['Completed cover', job.completed_cover_uuid ? <Link className="text-violet-300" to={`/completed-covers/${job.completed_cover_uuid}`}>Open</Link> : 'Not linked']]} /></section><section className="panel p-5"><h2 className="section-title">Files</h2><FieldList rows={[['CAD file', job.cad_file_url ? <a className="text-violet-300 underline" href={job.cad_file_url} target="_blank" rel="noreferrer">Open</a> : 'Not uploaded'], ['Print file', job.print_file_url ? <a className="text-violet-300 underline" href={job.print_file_url} target="_blank" rel="noreferrer">Open</a> : 'Not uploaded']]} /></section><section className="panel p-5"><h2 className="section-title">Print Settings</h2><FieldList rows={[['Printer', job.printer], ['Material', job.material], ['Nozzle', job.nozzle], ['Layer height', job.layer_height], ['Print time (h)', job.print_time_hours], ['Material used (g)', job.material_used_g], ['Started', job.started_date], ['Completed', job.completed_date]]} /></section><section className="panel p-5"><h2 className="section-title">Inspection</h2><FieldList rows={[['Inspection', job.inspection]]} /></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">{job.record_state === 'archived' ? <button disabled={busy} onClick={audited(() => manufacturingService.restore(job, 'Ray'))} className="btn-secondary"><RotateCcw />Restore job</button> : <button disabled={busy} onClick={audited(() => manufacturingService.archive(job, 'Ray'))} className="btn-secondary"><Archive />Archive job</button>}</div></>;
}