import { Camera, Ruler, Box, Sparkles, ShieldAlert, ShieldOff, AlertTriangle, CheckCircle2, FileText, User, Layers, Activity, Footprints } from 'lucide-react';
import StatusPill from '@/components/workshop/StatusPill';

const PART_INFO = {
  residual: { name: 'Residual Limb / Liner', category: 'Liner', icon: User },
  socket: { name: 'Socket', category: 'Socket', icon: Box },
  adapter: { name: 'Distal Socket Adapter', category: 'Adapter', icon: Activity },
  pylon: { name: 'Pylon', category: 'Pylon', icon: Activity },
  clamp: { name: 'Tube Clamp', category: 'Tube clamp', icon: Activity },
  ankle: { name: 'Ankle Adapter', category: 'Ankle', icon: Activity },
  foot: { name: 'Foot', category: 'Foot', icon: Footprints },
};

function Field({ label, value, unit, placeholder = 'Not recorded' }) {
  const has = value != null && value !== '' && !(typeof value === 'string' && value.trim() === '');
  return (
    <div className="flex items-baseline justify-between gap-3 border-b border-white/5 py-2">
      <span className="shrink-0 text-sm text-slate-400">{label}</span>
      <span className={`text-right text-sm font-semibold ${has ? 'text-slate-100' : 'italic text-slate-500'}`}>
        {has ? <>{value}{unit ? ` ${unit}` : ''}</> : placeholder}
      </span>
    </div>
  );
}

function Section({ title, icon, children }) {
  const Icon = icon;
  return (
    <div className="mb-4">
      <h3 className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">
        {Icon && <Icon className="h-3.5 w-3.5" />}{title}
      </h3>
      <div className="rounded-xl border border-white/10 bg-white/[0.02] p-3">{children}</div>
    </div>
  );
}

function CompletionBadge({ sessions, projectUuids }) {
  const rel = (sessions || []).filter(s => projectUuids.includes(s.project_uuid));
  let label = 'No measurement session';
  let cls = 'bg-slate-400/15 text-slate-300';
  if (rel.length > 0) {
    if (rel.some(s => s.status === 'Complete')) { label = 'Session complete'; cls = 'bg-emerald-400/15 text-emerald-300'; }
    else if (rel.some(s => s.status === 'In progress')) { label = 'In progress'; cls = 'bg-amber-400/15 text-amber-300'; }
    else if (rel.some(s => s.status === 'Review required')) { label = 'Review required'; cls = 'bg-amber-400/15 text-amber-300'; }
    else { label = rel[0].status || 'Not started'; }
  }
  return <span className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-semibold ${cls}`}><Activity className="h-3 w-3" />{label}</span>;
}

export default function ContextPanel({ selected, component, dimensions, stations, accessPoints, keepOutZones, movementPositions, missingInfo, context = {}, coverParams = {}, display = {} }) {
  const { customers = [], limbs = [], prostheses = [], projects = [], components = [], sessions = [] } = context;

  if (!selected) {
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3">
          <h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Context Controls</h2>
        </div>
        <div className="flex flex-1 items-center justify-center p-8 text-center">
          <div>
            <Camera className="mx-auto mb-3 h-10 w-10 text-slate-600" />
            <p className="text-sm text-slate-500">Select an object in the project tree or 3D viewport to view its properties and controls.</p>
          </div>
        </div>
      </div>
    );
  }

  // ---- Generic visual assembly part (socket, pylon, foot, …) ----
  if (selected.type === 'part') {
    const partId = selected.partId || selected.index;
    const info = PART_INFO[partId] || { name: selected.label || 'Part', category: 'Part', icon: Box };
    const Icon = info.icon;
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Assembly Part</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Icon className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{info.name}</h3></div>
          <Section title="Identification">
            <Field label="Manufacturer" value="Generic visual model" />
            <Field label="Model" value="Procedural below-knee assembly" />
            <Field label="Variant" value="Visual fallback" />
            <Field label="Category" value={info.category} />
            <Field label="Verification" value={<StatusPill tone="amber">Not manufacturing geometry</StatusPill>} />
          </Section>
          <div className="rounded-xl border border-amber-400/30 bg-amber-400/10 p-3 text-xs text-amber-200">
            <AlertTriangle className="mr-1.5 inline h-3.5 w-3.5" />Workshop measurement required — link a physical component record to load verified dimensions. Dimensions must be verified before CAD.
          </div>
        </div>
      </div>
    );
  }

  // ---- Customer ----
  if (selected.type === 'customer') {
    const c = selected.data || {};
    const custLimbs = limbs.filter(l => l.customer_uuid === c.uuid);
    const custProjects = projects.filter(p => p.customer_uuid === c.uuid);
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Customer</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><User className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{c.full_name || c.preferred_name || c.customer_number}</h3></div>
          <Section title="Identification">
            <Field label="Customer number" value={c.customer_number} />
            <Field label="Preferred name" value={c.preferred_name} />
            <Field label="Date of birth" value={c.date_of_birth} />
            <Field label="Pronouns" value={c.pronouns} />
          </Section>
          <Section title="Contact">
            <Field label="Email" value={c.email} />
            <Field label="Phone" value={c.phone} />
            <Field label="Preferred contact" value={c.preferred_contact_method} />
          </Section>
          <Section title="Funding">
            <Field label="Funding method" value={c.funding_method} />
            <Field label="Approval status" value={c.approval_status} />
            <Field label="NDIS number" value={c.ndis_number} placeholder="Not applicable" />
          </Section>
          <Section title="Limb profiles" icon={Layers}>
            {custLimbs.length === 0 ? <p className="text-sm italic text-slate-500">No limb profiles recorded</p> : custLimbs.map(l => (
              <div key={l.uuid} className="border-b border-white/5 py-2 text-sm"><span className="font-semibold text-slate-100">{l.profile_name || l.configuration}</span><div className="text-xs text-slate-400">{l.configuration} · {l.interface_type || 'Socket'}</div></div>
            ))}
          </Section>
          <Section title="Projects">
            {custProjects.length === 0 ? <p className="text-sm italic text-slate-500">No cover projects recorded</p> : custProjects.map(p => (
              <div key={p.uuid} className="flex items-center justify-between border-b border-white/5 py-2 text-sm"><span className="text-slate-100">{p.project_id}</span><span className="text-xs text-slate-400">{p.status}</span></div>
            ))}
          </Section>
          <div className="flex items-center justify-between py-1"><span className="text-sm text-slate-400">Measurement status</span><CompletionBadge sessions={sessions} projectUuids={custProjects.map(p => p.uuid)} /></div>
        </div>
      </div>
    );
  }

  // ---- Limb profile ----
  if (selected.type === 'limb') {
    const l = selected.data || {};
    const customer = customers.find(c => c.uuid === l.customer_uuid);
    const limbPros = prostheses.filter(p => p.limb_profile_uuid === l.uuid);
    const pro = limbPros[0];
    const limbProjects = projects.filter(p => p.limb_profile_uuid === l.uuid);
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Limb Profile</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Layers className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{l.profile_name || l.configuration}</h3></div>
          <Section title="Limb configuration">
            <Field label="Configuration" value={l.configuration} />
            <Field label="Side" value={l.side || (typeof l.configuration === 'string' && l.configuration.startsWith('Left') ? 'Left' : l.configuration?.startsWith('Right') ? 'Right' : null)} />
            <Field label="Amputation level" value={l.amputation_level || (typeof l.configuration === 'string' ? l.configuration.replace(/^(Left|Right)\s+/, '') : null)} />
            <Field label="Interface type" value={l.interface_type} />
            <Field label="Cover location" value={l.cover_location} />
          </Section>
          <Section title="Prosthesis">
            <Field label="Manufacturer" value={pro?.manufacturer || l.prosthesis_manufacturer} />
            <Field label="Model" value={pro?.model || l.prosthesis_model} />
            <Field label="Prosthetist / clinic" value={l.prosthetist_or_clinic} />
            <Field label="Fitting date" value={l.fitting_date || pro?.fitting_date} />
          </Section>
          <Section title="Customer">
            <Field label="Customer" value={customer?.full_name || customer?.preferred_name} />
            <Field label="Customer number" value={customer?.customer_number} />
          </Section>
          <Section title="Project">
            {limbProjects.length === 0 ? <p className="text-sm italic text-slate-500">No cover project recorded</p> : limbProjects.map(p => (
              <div key={p.uuid} className="flex items-center justify-between border-b border-white/5 py-2 text-sm"><span className="text-slate-100">{p.project_id}</span><span className="text-xs text-slate-400">{p.status}</span></div>
            ))}
          </Section>
          <div className="flex items-center justify-between py-1"><span className="text-sm text-slate-400">Measurement status</span><CompletionBadge sessions={sessions} projectUuids={limbProjects.map(p => p.uuid)} /></div>
          <div className="mt-3 rounded-xl border border-white/10 bg-white/[0.02] p-3 text-xs text-slate-400">
            Visual model: generic until a verified component model is loaded. No measurements are invented.
          </div>
        </div>
      </div>
    );
  }

  // ---- Prosthesis ----
  if (selected.type === 'prosthesis') {
    const p = selected.data || {};
    const customer = customers.find(c => c.uuid === p.customer_uuid);
    const limb = limbs.find(l => l.uuid === p.limb_profile_uuid);
    const linkedComps = (p.component_uuids || []).map(u => components.find(c => c.uuid === u)).filter(Boolean);
    const proProject = projects.find(pr => pr.prosthesis_uuid === p.uuid) || projects.find(pr => pr.customer_uuid === p.customer_uuid && pr.limb_profile_uuid === p.limb_profile_uuid);
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Prosthesis</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Box className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{p.name || `${p.manufacturer || ''} ${p.model || ''}`.trim() || 'Prosthesis'}</h3></div>
          <Section title="Identification">
            <Field label="Manufacturer" value={p.manufacturer} />
            <Field label="Model" value={p.model} />
            <Field label="Serial number" value={p.serial_number} />
            <Field label="Fitting date" value={p.fitting_date} />
            <Field label="Status" value={p.status} />
          </Section>
          <Section title="Customer & limb">
            <Field label="Customer" value={customer?.full_name || customer?.preferred_name} />
            <Field label="Customer number" value={customer?.customer_number} />
            <Field label="Limb profile" value={limb?.profile_name || limb?.configuration} />
            <Field label="Configuration" value={limb?.configuration} />
          </Section>
          <Section title="Components" icon={Box}>
            {linkedComps.length === 0 ? <p className="text-sm italic text-slate-500">No components linked — workshop measurement required</p> : linkedComps.map(c => (
              <div key={c.uuid} className="flex items-center justify-between border-b border-white/5 py-2 text-sm"><span className="text-slate-100">{c.category}: {c.manufacturer} {c.model}</span><span className="text-xs text-slate-400">{c.confidence}</span></div>
            ))}
          </Section>
          <Section title="Project">
            <Field label="Project ID" value={proProject?.project_id} />
            <Field label="Status" value={proProject?.status} />
          </Section>
        </div>
      </div>
    );
  }

  // ---- Measurement station (fallback path; browse mode uses MeasurementInspector) ----
  if (selected.type === 'station') {
    const s = selected.data || {};
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Measurement Station</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Ruler className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{s.name || s.station_name || `Station ${String((selected.index ?? 0) + 1).padStart(2, '0')}`}</h3></div>
          <Section title="Dimensions">
            <Field label="Height from origin" value={s.height?.toFixed ? s.height.toFixed(0) : s.height_from_origin_mm} unit="mm" />
            <Field label="Total width" value={s.total_width_mm || s.width} unit="mm" placeholder="Measurement required" />
            <Field label="Total depth" value={s.total_depth_mm || s.depth} unit="mm" placeholder="Measurement required" />
            <Field label="Clearance" value={s.clearance_requirement_mm} unit="mm" />
          </Section>
          <Section title="Source">
            <Field label="Source" value="Workshop measured" />
            <Field label="Confidence" value="High" />
            <Field label="Verification" value={<StatusPill tone="green">Verified</StatusPill>} />
          </Section>
        </div>
      </div>
    );
  }

  // ---- Component (real or placeholder) ----
  if (selected.type === 'component') {
    const c = component || selected.data || {};
    const dims = dimensions || [];
    const getVal = key => dims.find(d => d.dimension_key === key)?.value_mm;
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">{selected.placeholder ? 'Component (not linked)' : 'Component'}</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Box className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">{[c.manufacturer, c.model].filter(Boolean).join(' ') || selected.label || 'Component'}</h3></div>
          <Section title="Identification">
            <Field label="Manufacturer" value={c.manufacturer} placeholder={selected.placeholder ? 'Workshop measurement required' : 'Not recorded'} />
            <Field label="Model" value={c.model} placeholder={selected.placeholder ? 'Workshop measurement required' : 'Not recorded'} />
            <Field label="Variant" value={c.variant} />
            <Field label="Article number" value={c.article_number} />
            <Field label="Category" value={c.category || selected.category} />
            <Field label="Confidence" value={c.confidence} />
          </Section>
          <Section title="Manufacturer dimensions">
            <Field label="System height" value={getVal('system_height_mm')} unit="mm" placeholder="Workshop measurement required" />
            <Field label="Max width" value={getVal('overall_max_width')} unit="mm" placeholder="Workshop measurement required" />
            <Field label="Max depth" value={getVal('overall_max_depth')} unit="mm" placeholder="Workshop measurement required" />
          </Section>
          <Section title="Zones">
            <Field label="Access points" value={accessPoints?.length || 0} />
            <Field label="Keep-out zones" value={keepOutZones?.length || 0} />
            <Field label="Movement positions" value={movementPositions?.length || 0} />
          </Section>
          {missingInfo?.length > 0 && (
            <Section title="Missing information" icon={AlertTriangle}>
              <ul className="space-y-1.5">
                {missingInfo.map((m, i) => <li key={i} className="flex items-start gap-2 text-sm text-amber-300"><AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />{m}</li>)}
              </ul>
            </Section>
          )}
        </div>
      </div>
    );
  }

  // ---- Conceptual cover ----
  if (selected.type === 'cover') {
    const logoVisible = display.logo !== false;
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Cover Shell</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><Sparkles className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">Conceptual Cover</h3></div>
          <Section title="Geometry">
            <Field label="Global clearance" value={coverParams.clearance} unit="mm" />
            <Field label="Wall thickness" value={coverParams.wallThickness} unit="mm" />
            <Field label="Panel style" value={coverParams.shellType} />
            <Field label="Panel count" value={coverParams.panelCount} />
            <Field label="Seam orientation" value={coverParams.seamOrientation} />
          </Section>
          <Section title="Features">
            <Field label="Ventilation density" value={coverParams.ventilationDensity} unit="%" />
            <Field label="Material" value="Conceptual (PETG / ASA — not specified)" />
            <Field label="Cover transparency" value="Controlled by viewport transparency slider" />
          </Section>
          <Section title="Branding & CAD">
            <Field label="SHiRE logo status" value={logoVisible ? 'Visible' : 'Hidden — mandatory branding not shown'} />
            <Field label="Logo size" value={coverParams.logoSize} unit="mm" />
            <Field label="CAD status" value={<StatusPill tone="amber">Not ready — conceptual preview</StatusPill>} />
          </Section>
          <div className="rounded-xl border border-amber-400/30 bg-amber-400/10 p-3 text-xs text-amber-200">
            <strong>Conceptual preview</strong> — not manufacturing geometry. Print Ready unavailable until CAD geometry is connected.
          </div>
        </div>
      </div>
    );
  }

  // ---- Access / keep-out zones ----
  if (selected.type === 'access' || selected.type === 'keepout') {
    const z = selected.data || {};
    const isAccess = selected.type === 'access';
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">{isAccess ? 'Access Zone' : 'Keep-Out Zone'}</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2">{isAccess ? <ShieldAlert className="h-5 w-5 text-amber-400" /> : <ShieldOff className="h-5 w-5 text-red-400" />}<h3 className="text-lg font-semibold text-white">{z.name || 'Zone'}</h3></div>
          <Section title="Dimensions">
            <Field label="Width" value={z.width_mm} unit="mm" />
            <Field label="Height" value={z.height_mm} unit="mm" />
            <Field label="Depth" value={z.depth_mm} unit="mm" />
            <Field label="Clearance" value={z.required_clearance_mm || z.clearance_mm} unit="mm" />
          </Section>
          <Section title="Details">
            <Field label="Type" value={z.type} />
            <Field label="Position" value={z.position} />
            <Field label="Must remain accessible" value={z.must_remain_accessible ? 'Yes' : 'No'} />
          </Section>
          {z.notes && <Section title="Notes"><p className="text-sm text-slate-300">{z.notes}</p></Section>}
        </div>
      </div>
    );
  }

  // ---- Sensitive zone ----
  if (selected.type === 'sensitive') {
    const z = selected.data || {};
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Sensitive Zone</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><ShieldAlert className="h-5 w-5 text-purple-400" /><h3 className="text-lg font-semibold text-white">{z.label || z.type || 'Sensitive Zone'}</h3></div>
          <Section title="Properties">
            <Field label="Type" value={z.type} />
            <Field label="Sensitivity" value={z.sensitivity || 'Medium'} />
            <Field label="Contact permission" value={z.contactPermission || 'No contact'} />
            <Field label="Brush size" value={z.brushSize} unit="mm" />
            <Field label="Clearance depth" value={z.clearanceDepth} unit="mm" />
          </Section>
          {z.notes && <Section title="Notes"><p className="text-sm text-slate-300">{z.notes}</p></Section>}
        </div>
      </div>
    );
  }

  // ---- SHiRE logo ----
  if (selected.type === 'logo') {
    const logoVisible = display.logo !== false;
    return (
      <div className="flex h-full flex-col">
        <div className="border-b border-white/10 px-4 py-3"><h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">SHiRE Branding</h2></div>
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4 flex items-center gap-2"><FileText className="h-5 w-5 text-cyan-400" /><h3 className="text-lg font-semibold text-white">SHiRE Logo</h3></div>
          <Section title="Placement">
            <Field label="Position" value="Exterior front face" />
            <Field label="Width" value={coverParams.logoSize || 40} unit="mm" />
            <Field label="Depth" value={coverParams.logoDepth || 1.5} unit="mm" />
            <Field label="Style" value="Raised wordmark" />
            <Field label="Mandatory" value="Yes" />
          </Section>
          <Section title="Validation">
            {logoVisible ? (
              <div className="flex items-center gap-2 text-sm text-emerald-300"><CheckCircle2 className="h-4 w-4" /> Logo visible on approved surface</div>
            ) : (
              <div className="flex items-start gap-2 text-sm text-amber-300"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /> Mandatory logo is hidden — it must be visible before printing.</div>
            )}
            <div className="mt-2 text-xs text-slate-500">Logo snaps away from seams, hinges, clips, vents, and sensitive zones.</div>
          </Section>
        </div>
      </div>
    );
  }

  return null;
}