import { useEffect, useState } from 'react';
import { Ruler, Box, Layers, Footprints, ShieldAlert, Save, RotateCcw, Ban, History, CheckCircle2, AlertTriangle, XCircle } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { saveStationMeasurement, GEOMETRY_STATUS, STATUS_TONE } from '@/services/measurementGeometryService';

const STATION_LABELS = {
  'pylon': 'Pylon Diameter',
  'cover-lower': 'Cover Lower Circumference',
  'socket-distal': 'Socket Distal Circumference',
  'socket-middle': 'Socket Middle Circumference',
  'cover-widest': 'Widest Cover / Calf Region',
  'socket-upper': 'Socket Upper Circumference',
  'socket-proximal': 'Socket Proximal Boundary',
};

function Field({ label, value, hint }) {
  return (
    <div className="flex flex-col gap-0.5 py-1.5">
      <span className="text-[10px] font-semibold uppercase tracking-wider text-slate-500">{label}</span>
      <span className={`text-sm ${value == null || value === '' ? 'text-slate-600 italic' : 'text-slate-100'}`}>{value == null || value === '' ? (hint || 'Not recorded') : value}</span>
    </div>
  );
}

function Pill({ tone, children }) {
  const map = { green: 'border-emerald-400/40 bg-emerald-400/10 text-emerald-300', amber: 'border-amber-400/40 bg-amber-400/10 text-amber-300', red: 'border-red-400/40 bg-red-400/10 text-red-300', purple: 'border-violet-400/40 bg-violet-400/10 text-violet-300', slate: 'border-white/15 bg-white/5 text-slate-300' };
  return <span className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold ${map[tone] || map.slate}`}>{children}</span>;
}

export default function ContextInspectorV2({ selection, project, sessionId, componentUuid, geometry, onSaved }) {
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({ total_width_mm: '', total_depth_mm: '', circumference_mm: '', height_from_origin_mm: '', notes: '' });
  const [existing, setExisting] = useState(null);
  const [linkedComponent, setLinkedComponent] = useState(null);

  const kind = selection ? selection.type : null;
  const isStation = kind === 'measurementStation';
  const isPart = kind === 'prosthesisPart';
  const isCover = kind === 'cover';
  const partId = isPart ? selection.partId : isCover ? 'cover-shell' : null;

  // Load existing station value when a station is selected
  useEffect(() => {
    if (!isStation || !sessionId) return;
    let alive = true;
    const name = selection.stationName || STATION_LABELS[selection.stationId] || selection.stationId;
    base44.entities.EnvelopeStation.filter({ session_uuid: sessionId, station_name: name })
      .then((list) => {
        if (!alive) return;
        const rec = list && list[0];
        setExisting(rec || null);
        if (rec) {
          setForm({
            total_width_mm: rec.total_width_mm ?? '',
            total_depth_mm: rec.total_depth_mm ?? '',
            circumference_mm: rec.circumference_mm ?? '',
            height_from_origin_mm: rec.height_from_origin_mm ?? '',
            notes: rec.notes ?? '',
          });
        } else {
          setForm({ total_width_mm: '', total_depth_mm: '', circumference_mm: '', height_from_origin_mm: '', notes: '' });
        }
      })
      .catch(() => { if (alive) setExisting(null); });
    return () => { alive = false; };
  }, [isStation, sessionId, selection && selection.stationId]);

  // Load linked component for hardware parts
  useEffect(() => {
    if (!isPart || !project) return;
    const uuids = project.component_uuids || [];
    if (!uuids.length) { setLinkedComponent(null); return; }
    let alive = true;
    base44.entities.Component.filter({ uuid: { $in: uuids } })
      .then((list) => { if (alive) setLinkedComponent((list || [])[0] || null); })
      .catch(() => { if (alive) setLinkedComponent(null); });
    return () => { alive = false; };
  }, [isPart, project && project.uuid]);

  const handleSave = async () => {
    if (!isStation || !sessionId) return;
    setBusy(true);
    try {
      const name = selection.stationName || STATION_LABELS[selection.stationId] || selection.stationId;
      await saveStationMeasurement({
        sessionUuid: sessionId,
        componentUuid: componentUuid || (project && (project.component_uuids || [])[0]) || 'generic',
        station: {
          station_name: name,
          total_width_mm: form.total_width_mm,
          total_depth_mm: form.total_depth_mm,
          circumference_mm: form.circumference_mm,
          height_from_origin_mm: form.height_from_origin_mm,
          notes: form.notes,
        },
      });
      onSaved && onSaved();
    } finally { setBusy(false); }
  };

  const handleNotApplicable = async () => {
    if (!isStation || !sessionId) return;
    setBusy(true);
    try {
      const name = selection.stationName || STATION_LABELS[selection.stationId] || selection.stationId;
      await saveStationMeasurement({ sessionUuid: sessionId, componentUuid: componentUuid || 'generic', station: { station_name: name, notes: 'Not applicable', shape_classification: 'Not applicable' } });
      onSaved && onSaved();
    } finally { setBusy(false); }
  };

  const statusTone = geometry ? STATUS_TONE[geometry.geometryStatus] : 'slate';

  return (
    <div className="flex h-full flex-col">
      <div className="flex items-center gap-2 border-b border-shire-border px-4 py-3">
        <Ruler className="h-4 w-4 text-shire-purple-bright" />
        <span className="text-sm font-semibold text-slate-100">Workshop Inspector</span>
        {geometry && <Pill tone={statusTone}><span className="h-1.5 w-1.5 rounded-full bg-current" />{geometry.geometryStatus}</Pill>}
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
        {!selection && (
          <div className="space-y-3 py-8 text-center text-sm text-slate-500">
            <Ruler className="mx-auto h-8 w-8 text-slate-600" />
            <p>Select a station, part, or the cover in the viewport to inspect it.</p>
            <p className="text-xs text-slate-600">Measurement stations show live entry. Parts show component data. The cover shows geometry status.</p>
          </div>
        )}

        {isStation && (
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Pill tone="purple">Station</Pill>
              <h3 className="text-sm font-semibold text-white">{selection.stationName || STATION_LABELS[selection.stationId] || selection.stationId}</h3>
            </div>
            {existing ? <Pill tone="green"><CheckCircle2 className="h-3 w-3" />Recorded — review required</Pill> : <Pill tone="red"><XCircle className="h-3 w-3" />Measurement required</Pill>}
            <div className="grid grid-cols-2 gap-2">
              <NumberInput label="Width (mm)" value={form.total_width_mm} onChange={(v) => setForm((f) => ({ ...f, total_width_mm: v }))} />
              <NumberInput label="Depth (mm)" value={form.total_depth_mm} onChange={(v) => setForm((f) => ({ ...f, total_depth_mm: v }))} />
              <NumberInput label="Circumference (mm)" value={form.circumference_mm} onChange={(v) => setForm((f) => ({ ...f, circumference_mm: v }))} />
              <NumberInput label="Height from origin (mm)" value={form.height_from_origin_mm} onChange={(v) => setForm((f) => ({ ...f, height_from_origin_mm: v }))} />
            </div>
            <textarea placeholder="Notes" value={form.notes} onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))} className="workshop-input min-h-16" />
            <div className="flex flex-wrap gap-2 pt-1">
              <button onClick={handleSave} disabled={busy || !sessionId} className="btn-primary flex-1"><Save className="h-4 w-4" />Save & Continue</button>
              <button onClick={handleNotApplicable} disabled={busy} className="btn-secondary"><Ban className="h-4 w-4" />N/A</button>
            </div>
            <p className="text-[11px] text-slate-500">{sessionId ? 'Saves to the active measurement session and updates the 3D model.' : 'No active session — select or create a session first.'}</p>
          </div>
        )}

        {isPart && partId === 'socket' && (
          <div className="space-y-2">
            <SectionTitle icon={Box} text="Socket" />
            <Pill tone={statusTone}>{GEOMETRY_STATUS[geometry?.geometryStatus || 'generic']}</Pill>
            <Field label="Geometry status" value={geometry?.geometryStatus} hint="Generic" />
            <Field label="Cross-section stations recorded" value={geometry ? `${geometry.dimensionedCount} / 6+` : '0 / 6'} />
            <Field label="Source count" value={geometry?.sourceCount} hint="None" />
            {geometry && geometry.missing.length > 0 && (
              <div className="rounded-lg border border-amber-400/30 bg-amber-400/5 px-3 py-2 text-xs text-amber-300">
                {geometry.missing.map((m, i) => <div key={i}>• {m}</div>)}
              </div>
            )}
            <Field label="Trimline records" value="Asymmetric (lateral high, anterior low)" />
            <Field label="Source quality" value="Workshop measured" hint="Verification required" />
          </div>
        )}

        {isPart && partId === 'foot' && (
          <div className="space-y-2">
            <SectionTitle icon={Footprints} text="Prosthetic Foot" />
            <Field label="Foot model" hint="Manufacturer value unavailable" />
            <Field label="Foot length" hint="Measurement required" />
            <Field label="Maximum width" hint="Measurement required" />
            <Field label="Heel height" hint="Measurement required" />
            <Field label="Toe spring" hint="Measurement required" />
            <Field label="Ankle position" hint="Measurement required" />
            <Field label="Cover interference status" hint="Not assessed" />
          </div>
        )}

        {isPart && (partId === 'pylon' || partId === 'adapter' || partId === 'clamp' || partId === 'ankle' || partId === 'liner') && (
          <div className="space-y-2">
            <SectionTitle icon={Box} text={selection.label || partId} />
            {linkedComponent ? (
              <>
                <Field label="Manufacturer" value={linkedComponent.manufacturer} />
                <Field label="Model" value={linkedComponent.model} />
                <Field label="Variant" value={linkedComponent.variant} hint="Not recorded" />
                <Field label="Article number" value={linkedComponent.article_number} hint="Not recorded" />
                <Field label="Verification" value={linkedComponent.confidence} hint="Verification required" />
              </>
            ) : (
              <>
                <Pill tone="amber"><AlertTriangle className="h-3 w-3" />No component linked</Pill>
                <Field label="Manufacturer" hint="Manufacturer value unavailable" />
                <Field label="Exact model" hint="Verification required" />
                <Field label="Article number" hint="Not recorded" />
                <p className="text-[11px] text-slate-500">Link a component to this project in the Component Library to populate manufacturer values.</p>
              </>
            )}
          </div>
        )}

        {isCover && (
          <div className="space-y-2">
            <SectionTitle icon={Layers} text="Conceptual Cover" />
            <Pill tone={statusTone}>{GEOMETRY_STATUS[geometry?.geometryStatus || 'generic']}</Pill>
            <Field label="Geometry status" value={geometry?.geometryStatus} hint="Generic" />
            <Field label="Cover length" value={project?.cover_boundaries} hint="Not recorded" />
            <Field label="Global clearance" hint="Measurement required" />
            <Field label="Wall thickness target" hint="Not recorded" />
            <Field label="Opening direction" hint="Not recorded" />
            <Field label="Removal direction" hint="Not recorded" />
            <Field label="Material recommendation" value="ASA (UV/outdoor) — aesthetic, non-load-bearing" />
            <Field label="Ventilation" value={project?.design_preferences} hint="Not recorded" />
            <Pill tone="green"><CheckCircle2 className="h-3 w-3" />SHiRE branding: mandatory & present</Pill>
            <Field label="Design concept" hint="Not started — Design Forge" />
            <Field label="External CAD status" value="Not generated — visualisation only" />
            <div className="rounded-lg border border-amber-400/30 bg-amber-400/5 px-3 py-2 text-xs text-amber-300">
              <ShieldAlert className="mr-1 inline h-3 w-3" />Conceptual cover preview — not manufacturing geometry.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SectionTitle({ icon: Icon, text }) {
  return (
    <div className="flex items-center gap-2 pt-1">
      <Icon className="h-4 w-4 text-shire-purple-bright" />
      <h3 className="text-sm font-semibold text-white">{text}</h3>
    </div>
  );
}

function NumberInput({ label, value, onChange }) {
  return (
    <label className="flex flex-col gap-1">
      <span className="text-[10px] font-semibold uppercase tracking-wider text-slate-500">{label}</span>
      <input type="number" value={value} onChange={(e) => onChange(e.target.value)} className="workshop-input !mt-0 !min-h-9" />
    </label>
  );
}