import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { Link, useParams, useNavigate, useLocation } from 'react-router-dom';
import { Users, Eye, Receipt, ShoppingCart, ScanLine, Ruler, FileWarning, Copy, Sparkles } 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 BabylonViewportV2 from '@/components/viewportV2/BabylonViewportV2';
import { adapters } from '@/services/serviceConfig';
import { customerService } from '@/services/customerService';
import { projectService } from '@/services/projectService';
import { quoteService } from '@/services/quoteService';
import { orderService } from '@/services/orderService';
import { manufacturingService } from '@/services/manufacturingService';
import { completedCoverService } from '@/services/completedCoverService';
import { auditService } from '@/services/auditService';
import { designService } from '@/services/designService';
import { ossiguardService } from '@/services/ossiguardService';
import { loadProjectGeometry } from '@/services/measurementGeometryService';
import CustomDesignPanel from '@/components/design/CustomDesignPanel';
import OssiguardInspector from '@/components/ossiguard/OssiguardInspector';
import OssiguardValidation from '@/components/ossiguard/OssiguardValidation';
import OssiguardAssignPicker from '@/components/ossiguard/OssiguardAssignPicker';

const SECTIONS = [['customer','Customer'],['intake','Intake'],['measurements','Measurements'],['components','Components'],['ossiguard','Ossiguard'],['sensitive','Sensitive Zones'],['design','Design Brief'],['customDesign','Custom Design'],['validation','Validation'],['quote','Quote'],['order','Order'],['manufacturing','Manufacturing'],['covers','Completed Covers'],['audit','Audit']];

export default function ProjectDetail() {
  const { projectId } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [section, setSection] = useState(() => window.location.pathname.endsWith('/ossiguard') ? 'ossiguard' : 'customer');
  const [busy, setBusy] = useState(false);
  const [viewCommand, setViewCommand] = useState(null);
  const [mode] = useState('cover');
  const [showAllLabels, setShowAllLabels] = useState(false);
  const [humanReference, setHumanReference] = useState(false);
  const [compatibility, setCompatibility] = useState(false);
  const [geometry, setGeometry] = useState(null);
  const [diagnostics, setDiagnostics] = useState(null);
  const [designConfig, setDesignConfig] = useState(null);
  const [ossiguardProfile, setOssiguardProfile] = useState(null);
  const [showOssiguard, setShowOssiguard] = useState(true);
  const [assigningOssiguard, setAssigningOssiguard] = useState(false);
  const viewportRef = useRef(null);

  const load = useCallback(async () => {
    const project = await projectService.get(projectId);
    if (!project) { setData({ notFound: true }); return; }
    const [customer, limb, prostheses, allComponents, sessions, values, quotes, orders, jobs, covers, audits, design, designRevisions] = await Promise.all([
      project.customer_uuid ? customerService.get(project.customer_uuid) : Promise.resolve(null),
      project.limb_profile_uuid ? adapters.database.filter('LimbProfile', { uuid: project.limb_profile_uuid }, '-updated_date', 1) : Promise.resolve([]),
      project.customer_uuid ? adapters.database.filter('Prosthesis', { customer_uuid: project.customer_uuid }) : Promise.resolve([]),
      adapters.database.list('Component'),
      adapters.database.filter('MeasurementSession', { project_uuid: projectId }),
      adapters.database.filter('MeasurementValue', { project_uuid: projectId }),
      quoteService.forProject(projectId),
      orderService.forProject(projectId),
      manufacturingService.forProject(projectId),
      completedCoverService.forProject(projectId),
      auditService.list(),
      designService.getCurrent(projectId),
      designService.forProject(projectId),
    ]);
    const ossiguard = project.ossiguard_profile_uuid ? await ossiguardService.get(project.ossiguard_profile_uuid) : null;
    const componentUuids = project.component_uuids || [];
    const projectComponents = allComponents.filter((c) => componentUuids.includes(c.uuid));
    setGeometry(null);
    try { const geo = await loadProjectGeometry(projectId); setGeometry(geo); } catch (_) {}
    setDesignConfig(design || null);
    setOssiguardProfile(ossiguard);
    setData({ project, customer, limb: limb[0], prostheses, components: projectComponents, unknownComponents: componentUuids.length - projectComponents.length, sessions, values, quotes, orders, jobs, covers, design, designRevisions: designRevisions || [], ossiguard, audits: (audits || []).filter((a) => a.record_uuid === projectId).sort((a, b) => (b.created_date || '').localeCompare(a.created_date || '')) });
  }, [projectId]);

  useEffect(() => { load(); }, [load]);

  const refreshGeometry = useCallback(async () => { try { const geo = await loadProjectGeometry(projectId); setGeometry(geo); } catch (_) {} }, [projectId]);
  const fire = (preset) => setViewCommand({ preset, ts: Date.now() });
  const scrollToViewport = () => viewportRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });

  const act = (fn) => async (...args) => { setBusy(true); try { await fn(...args); await load(); await refreshGeometry(); } finally { setBusy(false); } };
  const prepareQuote = act(() => quoteService.create({ project_uuid: projectId, customer_uuid: data.project.customer_uuid, amount: 0, funding_type: 'Quote-only' }, 'Ray'));
  const saveDesign = act(async (form) => { await designService.saveRevision(projectId, { ...form, project_uuid: projectId, customer_uuid: data.project.customer_uuid }, 'Ray'); });
  const duplicateDesign = act(() => designService.duplicate(projectId, 'Ray'));
  const restoreDesign = act((uuid) => designService.restore(uuid, 'Ray'));
  const approveDesign = act(() => designService.approveForQuote(data.design.uuid, 'Ray'));
  const newStyleFromFit = act(async () => { const np = await projectService.duplicate(data.project, 'Ray'); await designService.copyToProject(projectId, np.uuid, 'Ray'); navigate(`/projects/${np.uuid}`); });
  const assignOssiguard = act(async (profile) => { await ossiguardService.assignToProject(data.project, profile, 'Ray'); setAssigningOssiguard(false); });
  const removeOssiguard = act(async () => { await ossiguardService.removeFromProject(data.project, 'Ray'); setShowOssiguard(false); });
  const reuseOssiguard = act(async (profileUuid) => { const np = await ossiguardService.reuseForCustomer(profileUuid, data.project.customer_uuid, 'Ray'); await ossiguardService.assignToProject(data.project, np, 'Ray'); });

  const validation = useMemo(() => {
    if (!data) return [];
    const p = data.project; const checks = [];
    checks.push(['Safety boundary accepted', !!p.safety_boundary_accepted, 'blocking']);
    checks.push(['Limb profile linked', !!data.limb, 'blocking']);
    checks.push(['Customer linked', !!data.customer, 'blocking']);
    checks.push(['At least one measurement session', data.sessions.length > 0, 'warning']);
    checks.push(['Measurements recorded', data.values.length > 0, 'warning']);
    checks.push(['Components identified', data.components.length > 0, 'warning']);
    checks.push(['No unknown components', data.unknownComponents === 0, 'warning']);
    checks.push(['Cover boundaries described', !!(p.cover_boundaries && p.cover_boundaries.trim()), 'warning']);
    checks.push(['Sensitive areas recorded', !!(p.sensitive_area_summary && p.sensitive_area_summary.trim()), 'warning']);
    checks.push(['Design preferences recorded', !!(p.design_preferences && p.design_preferences.trim()), 'warning']);
    checks.push(['Custom design saved', !!data.design, 'warning']);
    if (data.design) checks.push(['Design validation passed', data.design.validation_status === 'Pass', data.design.validation_status === 'Blocked' ? 'blocking' : 'warning']);
    if (data.design && data.design.custom_text_enabled && (data.design.custom_text || '').length > 24) checks.push(['Custom text length acceptable', false, 'warning']);
    if (p.ossiguard_attachment_method === 'SHiRE Ossiguard' || p.ossiguard_profile_uuid) {
      const ov = ossiguardService.validateProject(p, data.ossiguard, data.limb);
      checks.push(['Ossiguard profile selected', !!data.ossiguard, 'blocking']);
      checks.push(['Ossiguard validation passed', ov.level === 'pass', ov.level === 'blocked' ? 'blocking' : 'warning']);
      if (data.limb && data.limb.interface_type === 'Osseointegration') checks.push(['No stoma / implant attachment (osseointegration)', !(ov.issueObjects || []).some((i) => i.level === 'blocked' && i.text.toLowerCase().includes('implant')), 'blocking']);
    }
    checks.push(['Non-load-bearing cosmetic only', true, 'pass']);
    return checks;
  }, [data]);

  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">Project not found</h1><Link className="btn-secondary mt-4" to="/projects">Back to projects</Link></div>;
  const { project, customer, limb, prostheses, components, unknownComponents, sessions, values, quotes, orders, jobs, covers, design, designRevisions, ossiguard, audits } = data;

  return <><Breadcrumbs items={[{ label: 'Cover Projects', to: '/projects' }, { label: project.project_id }]} /><PageHeader eyebrow={`${project.project_id} · REV ${project.revision}`} title={customer?.full_name || 'Unknown customer'} description={`${project.prosthesis_configuration || 'Configuration not set'} · ${project.status}`} action={<div className="flex flex-wrap gap-2"><Link className="btn-primary" to={`/projects/${projectId}/design-forge`}><Sparkles />Open Design Forge</Link><button onClick={scrollToViewport} className="btn-secondary"><ScanLine />Open 3D Workshop</button><Link className="btn-secondary" to={`/customers/${project.customer_uuid}`}><Users />Open Customer</Link>{sessions[0] && <Link className="btn-secondary" to={`/measurements/${sessions[0].uuid}`}><Ruler />Open Measurements</Link>}<button disabled={busy} onClick={prepareQuote} className="btn-secondary"><Receipt />Prepare Quote</button>{orders[0] && <Link className="btn-secondary" to={`/orders/${orders[0].uuid}`}><ShoppingCart />View Order</Link>}</div>} /><div className="mb-5 flex flex-wrap items-center gap-2"><StatusPill tone={project.status === 'Complete' ? 'green' : 'amber'}>{project.status}</StatusPill>{geometry && <StatusPill tone={geometry.statusTone}>{geometry.geometryStatus}</StatusPill>}{quotes[0] && <StatusPill tone="cyan">Quote: {quotes[0].approval_status}</StatusPill>}{orders[0] && <StatusPill tone={orders[0].production_status === 'Complete' ? 'green' : 'amber'}>Order: {orders[0].production_status}</StatusPill>}{covers[0] && <StatusPill tone="green">Cover: {covers[0].cover_reference}</StatusPill>}<OriginBadge record={project} showAll /></div>

  <div ref={viewportRef} className="panel mb-5 overflow-hidden"><div className="flex flex-wrap items-center gap-2 border-b border-shire-border p-2">{['Front','Rear','Medial','Lateral','Top','Reset'].map((v) => <button key={v} onClick={() => fire(v.toLowerCase())} className="btn-secondary !py-1.5 !px-3 text-xs">{v}</button>)}<button onClick={() => setShowAllLabels((s) => !s)} className={`btn-secondary !py-1.5 text-xs ${showAllLabels ? '!border-violet-400/50 !text-violet-300' : ''}`}><Eye />{showAllLabels ? 'All labels' : 'Selected labels'}</button><button onClick={() => setHumanReference((h) => !h)} className={`btn-secondary !py-1.5 text-xs ${humanReference ? '!border-emerald-400/50 !text-emerald-300' : ''}`}>Human ref</button><button onClick={() => setCompatibility((c) => !c)} className={`btn-secondary !py-1.5 text-xs ${compatibility ? '!border-amber-400/50 !text-amber-300' : ''}`}>Compat</button>{ossiguard && <button onClick={() => setShowOssiguard((s) => !s)} className={`btn-secondary !py-1.5 text-xs ${showOssiguard ? '!border-violet-400/50 !text-violet-300' : ''}`}>Ossiguard</button>}<span className="ml-auto text-xs text-slate-500">{diagnostics?.renderLoopActive ? 'Viewport live' : 'Initialising'}</span></div><div className="h-[420px] lg:h-[520px] w-full bg-shire-viewport"><BabylonViewportV2 viewCommand={viewCommand} compatibility={compatibility} mode={mode} showAllLabels={showAllLabels} humanReference={humanReference} geometry={geometry} designConfig={designConfig} ossiguardProfile={ossiguardProfile} showOssiguard={showOssiguard} onDiagnostics={setDiagnostics} /></div></div>

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

  {section === 'customer' && <section className="panel p-5"><h2 className="section-title">Customer Summary</h2><FieldList rows={[['Customer', <Link className="text-violet-300" to={`/customers/${project.customer_uuid}`}>{customer?.full_name}</Link>], ['Customer number', customer?.customer_number], ['Email', customer?.email], ['Phone', customer?.phone], ['Funding method', customer?.funding_method], ['Approval status', customer?.approval_status]]} /></section>}
  {section === 'intake' && <section className="panel p-5"><h2 className="section-title">Public Intake Submission</h2>{project.data_origin === 'Public Intake' ? <FieldList columns={1} rows={[['Reason for cover', project.reason_for_cover], ['Cover boundaries', project.cover_boundaries], ['Sensitive area summary', project.sensitive_area_summary], ['Design preferences', project.design_preferences], ['Measurement method', project.measurement_method], ['Prosthesis configuration', project.prosthesis_configuration], ['Safety boundary accepted', project.safety_boundary_accepted ? 'Yes' : 'No']]} /> : <p className="text-sm text-slate-500">This project was created in the workshop (not from public intake). Original intake answers are not available.</p>}</section>}
  {section === 'measurements' && <section className="panel p-5"><h2 className="section-title">Measurement Sessions ({sessions.length}) · {values.length} values</h2>{sessions.length ? <div className="space-y-2">{sessions.map((s) => <div key={s.uuid} className="flex items-center justify-between rounded-lg border border-white/10 px-3 py-2"><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><Link className="btn-secondary !py-1 text-xs" to={`/measurements/${s.uuid}`}>Open session</Link></div></div>)}</div> : <p className="text-sm text-slate-500">No measurement sessions. {sessions[0] ? '' : <Link className="text-violet-300" to="/measurements">Go to Measurement Studio</Link>}.</p>}</section>}
  {section === 'components' && <section className="panel p-5"><h2 className="section-title">Installed Components</h2>{components.length ? <div className="space-y-2">{components.map((c) => <div key={c.uuid} className="rounded-lg border border-white/10 px-3 py-2 text-sm"><span className="font-medium text-slate-200">{c.manufacturer} {c.model}</span><span className="ml-2 text-xs text-slate-500">{c.category}</span><Link className="ml-3 text-xs text-violet-300" to={`/components/${c.uuid}/dimensions`}>Dimensions</Link></div>)}</div> : <p className="text-sm text-slate-500">No components linked to this project.</p>}{unknownComponents > 0 && <p className="mt-3 flex items-center gap-2 rounded-lg bg-amber-400/10 p-3 text-sm text-amber-200"><FileWarning />{unknownComponents} unknown component(s) referenced — no matching record found.</p>}</section>}
  {section === 'ossiguard' && <div className="space-y-5"><div className="panel p-5"><h2 className="section-title">Project Tree</h2><pre className="overflow-x-auto text-xs text-slate-300">{`Prosthetic Assembly
├── Socket / External Component${components.find((c) => c.category === 'Socket') ? ` (${components.find((c) => c.category === 'Socket').manufacturer} ${components.find((c) => c.category === 'Socket').model})` : ''}
├── Ossiguard Connector${ossiguard ? ` (${ossiguard.profile_name} rev${ossiguard.connector_revision})` : ' — not assigned'}
│   ├── Prosthesis Interface${ossiguard ? '' : ' — not assigned'}
│   ├── Cover Interface${ossiguard?.cover_side_interface ? ` (${ossiguard.cover_side_interface})` : ' — not set'}
│   ├── Attachment Points${ossiguard?.attachment_point_count ? ` (${ossiguard.attachment_point_count})` : ' — not set'}
│   ├── Release Mechanism${ossiguard?.release_method ? ` (${ossiguard.release_method})` : ' — not set'}
│   ├── Keep-Out Zones${ossiguard?.keep_out_zones ? '' : ' — see profile'}
│   └── Hardware${ossiguard?.fastener_type ? ` (${ossiguard.fastener_type})` : ' — not set'}
├── Pylon
├── Ankle
├── Foot
└── Cosmetic Cover`}</pre></div>{assigningOssiguard ? <OssiguardAssignPicker customer={customer} onAssign={assignOssiguard} onReuse={reuseOssiguard} onCancel={() => setAssigningOssiguard(false)} /> : <OssiguardInspector profile={ossiguard} project={project} busy={busy} onEdit={() => ossiguard && navigate(`/ossiguard/${ossiguard.uuid}`)} onAssign={() => setAssigningOssiguard(true)} onRemove={ossiguard ? removeOssiguard : null} onValidate={() => setSection('validation')} />}<div className="panel p-5"><h2 className="section-title">Ossiguard Validation</h2><OssiguardValidation profile={ossiguard} project={project} limb={limb} /></div></div>}
  {section === 'sensitive' && <section className="panel p-5"><h2 className="section-title">Sensitive Zones</h2><FieldList columns={1} rows={[['Submitted sensitive-area summary', project.sensitive_area_summary]]} /></section>}
  {section === 'design' && <section className="panel p-5"><h2 className="section-title">Design Brief</h2><FieldList columns={1} rows={[['Design preferences', project.design_preferences], ['Cover boundaries', project.cover_boundaries], ['Reason for cover', project.reason_for_cover]]} /></section>}
  {section === 'customDesign' && <><div className="mb-4 flex flex-wrap gap-2"><button onClick={scrollToViewport} className="btn-secondary"><ScanLine />Preview Design</button><button disabled={busy} onClick={newStyleFromFit} className="btn-secondary"><Copy />Create New Style from Existing Fit</button></div><CustomDesignPanel project={project} design={design} revisions={designRevisions} busy={busy} onSave={saveDesign} onDuplicate={duplicateDesign} onRestore={restoreDesign} onApprove={approveDesign} onPreview={scrollToViewport} onChange={setDesignConfig} /></>}
  {section === 'validation' && <section className="panel p-5"><h2 className="section-title">Validation Checks</h2><ul className="space-y-2">{validation.map(([label, pass, level]) => <li key={label} className="flex items-center gap-2 text-sm"><StatusPill tone={pass ? 'green' : level === 'blocking' ? 'red' : 'amber'}>{pass ? 'Passed' : level === 'blocking' ? 'Blocking' : 'Warning'}</StatusPill><span className="text-slate-300">{label}</span></li>)}</ul></section>}
  {section === 'quote' && <section className="panel p-5"><h2 className="section-title">Quote</h2>{quotes.length ? quotes.map((q) => <div key={q.uuid} className="rounded-lg border border-white/10 p-3"><FieldList rows={[['Quote number', q.quote_number], ['Amount', q.amount != null ? `$${q.amount}` : null], ['Funding type', q.funding_type], ['Approval', q.approval_status], ['Sent', q.sent_date], ['Expiry', q.expiry_date]]} /></div>) : <div><p className="text-sm text-slate-500">No quote yet.</p><button disabled={busy} onClick={prepareQuote} className="btn-secondary mt-3"><Receipt />Prepare quote</button></div>}</section>}
  {section === 'order' && <section className="panel p-5"><h2 className="section-title">Order</h2>{orders.length ? orders.map((o) => <div key={o.uuid} className="rounded-lg border border-white/10 p-3"><FieldList rows={[['Order', <Link className="text-violet-300" to={`/orders/${o.uuid}`}>{o.order_number}</Link>], ['Production', o.production_status], ['Payment', o.payment_status], ['Shipping', o.shipping_status], ['Balance', o.balance != null ? `$${o.balance}` : null]]} /></div>) : <p className="text-sm text-slate-500">No order yet. An order should only be created after the quote is approved.</p>}</section>}
  {section === 'manufacturing' && <section className="panel p-5"><h2 className="section-title">Manufacturing Jobs ({jobs.length})</h2>{jobs.length ? 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>) : <p className="text-sm text-slate-500">No manufacturing jobs. Manufacturing records appear once the project reaches the production stage.</p>}</section>}
  {section === 'covers' && <section className="panel p-5"><h2 className="section-title">Completed Covers ({covers.length})</h2>{covers.length ? 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"><span className="font-medium text-violet-300">{c.cover_reference} · {c.design_name}</span><StatusPill tone={c.inspection_result === 'Passed' ? 'green' : 'amber'}>{c.inspection_result || 'Pending'}</StatusPill></Link>) : <p className="text-sm text-slate-500">No completed covers yet.</p>}</section>}
  {section === 'audit' && <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>}
  </>;
}