import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { Copy, RefreshCw, AlertTriangle, FileDown, Archive } 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 { Image } from '@/components/ui/image';
import { completedCoverService } from '@/services/completedCoverService';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { auditService } from '@/services/auditService';
import { designService } from '@/services/designService';
import { ossiguardService, SAFETY_BANNER } from '@/services/ossiguardService';
export default function CompletedCoverDetail() {
  const { coverId } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [busy, setBusy] = useState(false);
  const load = async () => {
    const cover = await completedCoverService.get(coverId);
    const [customer, project, audits, design] = await Promise.all([
      cover?.customer_uuid ? customerService.get(cover.customer_uuid) : Promise.resolve(null),
      cover?.project_uuid ? projectService.get(cover.project_uuid) : Promise.resolve(null),
      auditService.list(),
      cover?.project_uuid ? designService.getCurrent(cover.project_uuid) : Promise.resolve(null),
    ]);
    const ossiguard = cover?.ossiguard_profile_uuid ? await ossiguardService.get(cover.ossiguard_profile_uuid) : null;
    setData({ cover, customer, project, design, ossiguard, audits: (audits || []).filter((a) => a.record_uuid === coverId).sort((a, b) => (b.created_date || '').localeCompare(a.created_date || '')) });
  };
  useEffect(() => { load(); }, [coverId]);
  if (!data) return <LoadingPanel />;
  const { cover, customer, project, design, ossiguard, audits } = data;
  const run = (fn) => async () => { setBusy(true); try { const r = await fn(); await load(); return r; } finally { setBusy(false); } };
  const reorder = run(async () => { const r = await completedCoverService.reorder(cover, 'Ray'); navigate(`/orders/${r.order.uuid}`); });
  const newDesign = run(async () => { const p = await completedCoverService.newDesignFromFit(cover, project, 'Ray'); navigate(`/projects/${p.uuid}`); });
  const replace = run(async () => { const order = await completedCoverService.replace(cover, 'Ray'); navigate(`/orders/${order.uuid}`); });
  const reportIssue = run(() => { const note = prompt('Describe the fit issue:'); return note && completedCoverService.reportFitIssue(cover, note, 'Ray'); });
  const exportReport = () => { const blob = new Blob([JSON.stringify({ cover, customer, project }, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${cover.cover_reference}.json`; a.click(); URL.revokeObjectURL(url); };
  return <><Breadcrumbs items={[{ label: 'Completed Covers', to: '/completed-covers' }, { label: cover.cover_reference }]} /><PageHeader eyebrow={cover.cover_reference} title={cover.design_name || 'Completed cover'} description={`${customer?.full_name || 'Unknown'} · ${project?.project_id || 'No project'}`} action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to={`/customers/${cover.customer_uuid}`}>Open Customer</Link><Link className="btn-secondary" to={`/projects/${cover.project_uuid}`}>Open Original Project</Link><button disabled={busy} onClick={reorder} className="btn-secondary"><RefreshCw />Reorder Exact Cover</button><button disabled={busy} onClick={newDesign} className="btn-secondary"><Copy />New Style from Fit</button><button disabled={busy} onClick={replace} className="btn-secondary"><Copy />Create Replacement</button><button disabled={busy} onClick={reportIssue} className="btn-secondary"><AlertTriangle />Report Fit Issue</button><button disabled={busy} onClick={exportReport} className="btn-secondary"><FileDown />Export Report</button></div>} /><div className="mb-5"><OriginBadge record={cover} showAll /></div><div className="grid gap-5 lg:grid-cols-3"><div className="panel overflow-hidden"><div className="aspect-square w-full bg-shire-viewport">{cover.preview_image_url ? <Image src={cover.preview_image_url} fittingType="fit" className="h-full w-full" /> : <div className="flex h-full items-center justify-center text-sm text-slate-600">No preview image recorded</div>}</div></div><div className="lg:col-span-2 grid gap-5 sm:grid-cols-2"><section className="panel p-5"><h2 className="section-title">Identity</h2><FieldList rows={[['Cover reference', cover.cover_reference], ['Revision', cover.revision], ['Design name', cover.design_name], ['SHiRE logo', cover.shire_logo_status], ['Reorder status', cover.reorder_status]]} /></section><section className="panel p-5"><h2 className="section-title">Material & Print</h2><FieldList rows={[['Material', cover.material], ['Filament brand', cover.filament_brand], ['Filament colour', cover.filament_colour], ['Main colour', cover.main_colour], ['Batch', cover.batch], ['Printer', cover.printer], ['Nozzle', cover.nozzle], ['Layer height', cover.layer_height], ['Print time (h)', cover.print_time_hours], ['Material used (g)', cover.material_used_g]]} /></section><section className="panel p-5"><h2 className="section-title">Post-processing & Inspection</h2><FieldList rows={[['Hardware', cover.hardware], ['Post-processing', cover.post_processing], ['Inspection result', <StatusPill tone={cover.inspection_result === 'Passed' ? 'green' : cover.inspection_result === 'Failed' ? 'red' : 'amber'}>{cover.inspection_result || 'Pending'}</StatusPill>], ['Fit review', <StatusPill tone={cover.fit_review_result === 'Good fit' ? 'green' : cover.fit_review_result === 'Refit required' ? 'red' : 'amber'}>{cover.fit_review_result || 'Not reviewed'}</StatusPill>]]} /></section><section className="panel p-5 sm:col-span-2"><h2 className="section-title">Approved Custom Design</h2>{design ? <><div className="grid gap-5 sm:grid-cols-2"><FieldList rows={[['Design category', design.design_category], ['Primary style', design.primary_style], ['Pattern style', design.pattern_style], ['Accent style', design.accent_style], ['Accent density', design.accent_density], ['Symmetry', design.symmetry], ['Finish', design.finish]]} /><FieldList rows={[['Main colour', design.main_colour], ['Accent colour', design.accent_colour], ['Logo colour', design.logo_colour], ['Logo placement', design.logo_placement], ['Logo size', design.logo_size], ['Text colour', design.text_colour]]} /></div>{design.custom_text_enabled && <div className="mt-4 rounded-lg border border-violet-400/30 bg-violet-400/5 p-4"><p className="text-xs font-semibold uppercase tracking-wide text-violet-300">Custom text</p><p className="mt-1 text-lg font-medium text-white">{design.custom_text || '—'}</p><p className="mt-1 text-xs text-slate-500">{design.text_style} · {design.text_placement} · {design.text_size} · {design.text_raised ? 'raised' : 'engraved'}</p></div>}{(design.surface_notes || design.inspiration_notes || design.vent_concept) && <div className="mt-4"><FieldList columns={1} rows={[['Surface notes', design.surface_notes], ['Inspiration notes', design.inspiration_notes], ['Vent concept', design.vent_concept]]} /></div>}<p className="mt-3 text-xs text-slate-500">Design revision v{design.version} · {design.approved_for_quote ? 'Approved for quote' : 'Not yet approved'} · Conceptual only — not manufacturing CAD.</p></> : <p className="text-sm text-slate-500">No custom design configuration saved for this project. <Link className="text-violet-300" to={`/projects/${cover.project_uuid}`}>Open project to add design</Link>.</p>}</section>
<section className="panel p-5 sm:col-span-2"><h2 className="section-title">Ossiguard Connector</h2><div className="mb-3 rounded-lg border border-violet-400/30 bg-violet-400/5 p-3 text-xs text-violet-200">{SAFETY_BANNER}</div>{cover.ossiguard_used || ossiguard ? <FieldList columns={2} rows={[['Ossiguard used', 'Yes'], ['Profile', ossiguard?.profile_name || cover.ossiguard_profile_label || '—'], ['Revision', cover.ossiguard_revision ? `rev${cover.ossiguard_revision}` : '—'], ['Connected component', cover.ossiguard_connected_component || '—'], ['Cover interface type', cover.cover_interface_type || ossiguard?.cover_side_interface || '—'], ['Hardware used', cover.ossiguard_hardware_used || '—'], ['Installation method', cover.ossiguard_installation_method || '—'], ['Removal method', cover.ossiguard_removal_method || '—'], ['Inspection result', cover.inspection_result || 'Pending'], ['Replacement compatibility', cover.ossiguard_replacement_compatibility || 'Compatible'], ['Reorder compatibility', cover.ossiguard_reorder_compatibility || 'Compatible']]} /> : <p className="text-sm text-slate-500">This cover was not recorded with an Ossiguard connector.</p>}</section>
<section className="panel p-5"><h2 className="section-title">Delivery</h2><FieldList rows={[['Completion date', cover.completion_date], ['Delivery date', cover.delivery_date]]} /></section><section className="panel p-5 sm:col-span-2"><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>}{cover.notes && <p className="mt-4 rounded-lg bg-amber-400/10 p-3 text-sm text-amber-100">{cover.notes}</p>}</section></div></div><div className="mt-5"><button disabled={busy} onClick={run(() => completedCoverService.archive(cover, 'Ray'))} className="btn-secondary"><Archive />Archive cover</button></div></>;
}