import { useEffect, useState, useCallback } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, ArrowRight, Save, CheckCircle2, ShieldCheck, AlertTriangle } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import Breadcrumbs from '@/components/workshop/Breadcrumbs';
import StatusPill from '@/components/workshop/StatusPill';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { ossiguardService, SAFETY_BANNER, PROHIBITED_ATTACH_TARGETS } from '@/services/ossiguardService';
import { adapters } from '@/services/serviceConfig';
import { base44 } from '@/api/base44Client';

const STEPS = [
  { id: 'context', title: 'Connector Context' },
  { id: 'receiving', title: 'Receiving Component' },
  { id: 'profile', title: 'Connector Profile' },
  { id: 'dimensions', title: 'Physical Dimensions' },
  { id: 'retention', title: 'Retention & Release' },
  { id: 'hardware', title: 'Hardware & Materials' },
  { id: 'clearances', title: 'Clearances' },
  { id: 'safety', title: 'Safety Confirmation' },
  { id: 'files', title: 'Files & CAD' },
  { id: 'review', title: 'Review & Approval' },
];

const blank = {
  profile_name: '', version: 'v1', connector_revision: 1, approval_status: 'Prototype', geometry_status: 'Visual Reference',
  designed_by: '', date_created: new Date().toISOString().slice(0, 10),
  compatible_limb_type: '', compatible_prosthesis_type: '', compatible_component_models: '',
  customer_uuid: '', attaches_to_component_uuid: '', attaches_to_component_label: '',
  approved_contact_surfaces: '', prohibited_contact_surfaces: '',
  overall_width_mm: '', overall_depth_mm: '', overall_height_mm: '', mount_centre_position: '',
  proximal_position_mm: '', distal_position_mm: '', medial_offset_mm: '', lateral_offset_mm: '',
  anterior_offset_mm: '', posterior_offset_mm: '', rotation_degrees: '',
  attachment_point_count: '', attachment_point_coordinates: '', fastener_spacing_mm: '', hole_diameters_mm: '',
  clip_dimensions: '', receiver_dimensions: '',
  retention_method: '', release_method: '', insertion_direction: '', removal_direction: '',
  anti_rotation_feature: '', secondary_retention: '', mechanical_stop: '', flexible_insert: false, cover_side_interface: '',
  main_connector_material: '', flexible_insert_material: '', fastener_type: '', fastener_size: '', washer_type: '', thread_type: '',
  hardware_quantity: '', recommended_print_material: '', printer_profile: '', hardware_notes: '',
  required_installation_clearance_mm: '', required_cover_clearance_mm: '', fastener_access: '', release_access: '',
  emergency_release_clearance_mm: '', hardware_protrusion_envelope: '',
  safety_no_implant: false, safety_no_abutment: false, safety_no_stoma: false, safety_no_skin: false,
  safety_no_alignment: false, safety_no_release: false, safety_no_movement: false, safety_no_maintenance: false,
  step_file_url: '', stl_file_url: '', three_mf_file_url: '', glb_preview_url: '',
  technical_drawing_url: '', photograph_url: '', assembly_diagram_url: '', validation_report_url: '',
  file_checksum: '', keep_out_zones: '', missing_dimensions: '', revision_notes: '', notes: '',
};

export default function OssiguardWizard() {
  const { connectorId } = useParams();
  const navigate = useNavigate();
  const isEdit = !!connectorId;
  const [step, setStep] = useState(0);
  const [form, setForm] = useState(blank);
  const [existing, setExisting] = useState(null);
  const [loading, setLoading] = useState(isEdit);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    if (!isEdit) { setLoading(false); return; }
    const p = await ossiguardService.get(connectorId);
    if (p) { setForm({ ...blank, ...p }); setExisting(p); }
    setLoading(false);
  }, [connectorId, isEdit]);
  useEffect(() => { load(); }, [load]);

  const set = (key, value) => setForm((f) => ({ ...f, [key]: value }));
  const setObj = (patch) => setForm((f) => ({ ...f, ...patch }));

  const validation = ossiguardService.validate(form, null);

  const save = async (action) => {
    setBusy(true); setError('');
    try {
      let status = form.approval_status;
      if (action === 'verify') status = 'Workshop Verified';
      if (action === 'approve') status = 'Approved Connector Revision';
      if (action === 'supersede') status = 'Superseded';
      const payload = { ...form, approval_status: status };
      if (action === 'approve' && validation.level === 'blocked') { setError('Cannot approve — blocking validation failures remain.'); return; }
      let record;
      if (isEdit) {
        record = await ossiguardService.update(existing, payload, 'Ray');
      } else {
        record = await ossiguardService.create(payload, 'Ray');
      }
      navigate(`/ossiguard/${record.uuid}`);
    } catch (e) { setError(e?.message || 'Save failed'); }
    finally { setBusy(false); }
  };

  if (loading) return <LoadingPanel label="Loading Ossiguard wizard" />;

  const Step = STEPS[step];

  return (
    <>
      <Breadcrumbs items={[{ label: 'Ossiguard Library', to: '/ossiguard' }, { label: isEdit ? 'Edit' : 'New Wizard' }]} />
      <PageHeader eyebrow={`Step ${step + 1} of ${STEPS.length}`} title={isEdit ? `Edit ${form.profile_name || 'Ossiguard'}` : 'Ossiguard Connector Wizard'} description="Record exact connector dimensions and safety confirmation. Dimensions stored in millimetres." action={<Link className="btn-secondary" to="/ossiguard"><ArrowLeft className="h-4 w-4" />Cancel</Link>} />

      <div className="mb-4 flex flex-wrap items-center gap-1.5">
        {STEPS.map((s, i) => (
          <button key={s.id} onClick={() => setStep(i)} className={`rounded-lg px-2.5 py-1.5 text-xs font-medium transition ${i === step ? 'bg-shire-purple text-white' : i < step ? 'border border-emerald-400/40 text-emerald-300' : 'border border-shire-border text-slate-500'}`}>{i + 1}. {s.title}</button>
        ))}
      </div>

      <div className="mb-4 rounded-lg border border-violet-400/30 bg-violet-400/5 p-3 text-xs text-violet-200"><ShieldCheck className="mr-1.5 inline h-4 w-4" />{SAFETY_BANNER}</div>

      <div className="panel mb-4 p-5">
        <h2 className="mb-4 text-base font-semibold text-white">{Step.title}</h2>
        {step === 0 && <ContextStep form={form} set={set} />}
        {step === 1 && <ReceivingStep form={form} set={set} />}
        {step === 2 && <ProfileStep form={form} set={set} />}
        {step === 3 && <DimensionsStep form={form} set={set} />}
        {step === 4 && <RetentionStep form={form} set={set} />}
        {step === 5 && <HardwareStep form={form} set={set} />}
        {step === 6 && <ClearanceStep form={form} set={set} />}
        {step === 7 && <SafetyStep form={form} set={set} />}
        {step === 8 && <FilesStep form={form} set={set} />}
        {step === 9 && <ReviewStep form={form} validation={validation} />}
        {error && <p className="mt-3 text-sm text-red-300">{error}</p>}
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <button disabled={step === 0} onClick={() => setStep((s) => Math.max(0, s - 1))} className="btn-secondary"><ArrowLeft className="h-4 w-4" />Back</button>
        {step < STEPS.length - 1 && <button onClick={() => setStep((s) => Math.min(STEPS.length - 1, s + 1))} className="btn-primary">Continue<ArrowRight className="h-4 w-4" /></button>}
        {step === STEPS.length - 1 && (
          <>
            <button disabled={busy} onClick={() => save('draft')} className="btn-secondary"><Save className="h-4 w-4" />Save Draft</button>
            <button disabled={busy} onClick={() => save('verify')} className="btn-secondary">Request Verification</button>
            <button disabled={busy} onClick={() => save('verify')} className="btn-secondary">Mark Workshop Verified</button>
            <button disabled={busy} onClick={() => save('approve')} className="btn-primary"><CheckCircle2 className="h-4 w-4" />Approve Revision</button>
          </>
        )}
      </div>
    </>
  );
}

function Field({ label, children, full }) { return <div className={full ? 'sm:col-span-2 lg:col-span-3' : ''}><label className="text-xs font-medium uppercase tracking-wide text-slate-400">{label}</label>{children}</div>; }
function TextInput({ label, value, onChange, type = 'text', placeholder, full }) { return <Field label={label} full={full}><input type={type} className="workshop-input" value={value ?? ''} onChange={(e) => onChange(type === 'number' ? (e.target.value === '' ? '' : Number(e.target.value)) : e.target.value)} placeholder={placeholder} /></Field>; }
function Select({ label, value, onChange, options, full }) { return <Field label={label} full={full}><select className="workshop-input" value={value || ''} onChange={(e) => onChange(e.target.value)}>{options.map((o) => <option key={o} value={o}>{o}</option>)}</select></Field>; }
function Toggle({ label, checked, onChange }) { return <label className="choice-card cursor-pointer"><input type="checkbox" checked={!!checked} onChange={(e) => onChange(e.target.checked)} className="h-5 w-5 accent-shire-purple" /><span>{label}</span></label>; }
function Grid({ children }) { return <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{children}</div>; }

function ContextStep({ form, set }) {
  return <Grid><TextInput label="Profile name" value={form.profile_name} onChange={(v) => set('profile_name', v)} full /><TextInput label="Version" value={form.version} onChange={(v) => set('version', v)} /><TextInput label="Revision" type="number" value={form.connector_revision} onChange={(v) => set('connector_revision', v)} /><Select label="Template / approval status" value={form.approval_status} onChange={(v) => set('approval_status', v)} options={['Prototype', 'Measurement Required', 'Workshop Verified', 'CAD Verified', 'Approved Connector Revision']} /><TextInput label="Designed by" value={form.designed_by} onChange={(v) => set('designed_by', v)} /><TextInput label="Date created" type="date" value={form.date_created} onChange={(v) => set('date_created', v)} /></Grid>;
}
function ReceivingStep({ form, set }) {
  return <div className="space-y-3"><Grid><TextInput label="Manufacturer" value={form.compatible_component_models} onChange={(v) => set('compatible_component_models', v)} full /><TextInput label="Exact model" value={form.compatible_prosthesis_type} onChange={(v) => set('compatible_prosthesis_type', v)} /><TextInput label="Component label" value={form.attaches_to_component_label} onChange={(v) => set('attaches_to_component_label', v)} full /><TextInput label="Approved external attachment region" value={form.approved_contact_surfaces} onChange={(v) => set('approved_contact_surfaces', v)} full /><TextInput label="Prohibited regions" value={form.prohibited_contact_surfaces} onChange={(v) => set('prohibited_contact_surfaces', v)} full /></Grid><div className="rounded-lg border border-red-400/30 bg-red-400/5 p-3 text-xs text-red-200"><AlertTriangle className="mr-1.5 inline h-3.5 w-3.5" />Prohibited attachment targets: {PROHIBITED_ATTACH_TARGETS.join(', ')}</div></div>;
}
function ProfileStep({ form, set }) {
  return <Grid><TextInput label="Compatible limb type" value={form.compatible_limb_type} onChange={(v) => set('compatible_limb_type', v)} /><TextInput label="Side" value={form.compatible_limb_type} onChange={() => {}} /><Select label="Interface" value={form.cover_side_interface ? 'Socket' : ''} onChange={() => {}} options={['Socket', 'Osseointegration']} /><TextInput label="Compatible component models" value={form.compatible_component_models} onChange={(v) => set('compatible_component_models', v)} full /><Select label="Cover-side interface" value={form.cover_side_interface} onChange={(v) => set('cover_side_interface', v)} options={['Two-piece clam shell', 'Front and rear shell', 'Left and right shell', 'Hinged cover', 'Slide-on panel', 'Clip-on panel', 'Replaceable outer panel', 'Modular armour plates']} /></Grid>;
}
function DimensionsStep({ form, set }) {
  return <Grid><TextInput label="Overall width (mm)" type="number" value={form.overall_width_mm} onChange={(v) => set('overall_width_mm', v)} /><TextInput label="Overall depth (mm)" type="number" value={form.overall_depth_mm} onChange={(v) => set('overall_depth_mm', v)} /><TextInput label="Overall height (mm)" type="number" value={form.overall_height_mm} onChange={(v) => set('overall_height_mm', v)} /><TextInput label="Mount centre position" value={form.mount_centre_position} onChange={(v) => set('mount_centre_position', v)} /><TextInput label="Proximal position (mm)" type="number" value={form.proximal_position_mm} onChange={(v) => set('proximal_position_mm', v)} /><TextInput label="Distal position (mm)" type="number" value={form.distal_position_mm} onChange={(v) => set('distal_position_mm', v)} /><TextInput label="Medial offset (mm)" type="number" value={form.medial_offset_mm} onChange={(v) => set('medial_offset_mm', v)} /><TextInput label="Lateral offset (mm)" type="number" value={form.lateral_offset_mm} onChange={(v) => set('lateral_offset_mm', v)} /><TextInput label="Anterior offset (mm)" type="number" value={form.anterior_offset_mm} onChange={(v) => set('anterior_offset_mm', v)} /><TextInput label="Posterior offset (mm)" type="number" value={form.posterior_offset_mm} onChange={(v) => set('posterior_offset_mm', v)} /><TextInput label="Rotation (degrees)" type="number" value={form.rotation_degrees} onChange={(v) => set('rotation_degrees', v)} /><TextInput label="Attachment point count" type="number" value={form.attachment_point_count} onChange={(v) => set('attachment_point_count', v)} /><TextInput label="Attachment point coordinates" value={form.attachment_point_coordinates} onChange={(v) => set('attachment_point_coordinates', v)} full /><TextInput label="Fastener spacing (mm)" type="number" value={form.fastener_spacing_mm} onChange={(v) => set('fastener_spacing_mm', v)} /><TextInput label="Hole diameters (mm)" value={form.hole_diameters_mm} onChange={(v) => set('hole_diameters_mm', v)} /><TextInput label="Clip dimensions" value={form.clip_dimensions} onChange={(v) => set('clip_dimensions', v)} /><TextInput label="Receiver dimensions" value={form.receiver_dimensions} onChange={(v) => set('receiver_dimensions', v)} /></Grid>;
}
function RetentionStep({ form, set }) {
  return <Grid><Select label="Retention method" value={form.retention_method} onChange={(v) => set('retention_method', v)} options={['', 'Screw fasteners', 'Captive clips', 'Alignment pins + clips', 'Flexible receiver insert', 'Replaceable tabs', 'Secondary safety retention', 'Custom']} /><Select label="Release method" value={form.release_method} onChange={(v) => set('release_method', v)} options={['', 'Lateral slide', 'Proximal pull', 'Clip release', 'Screw release', 'Tool-free release', 'Custom']} /><TextInput label="Insertion direction" value={form.insertion_direction} onChange={(v) => set('insertion_direction', v)} /><TextInput label="Removal direction" value={form.removal_direction} onChange={(v) => set('removal_direction', v)} /><TextInput label="Anti-rotation feature" value={form.anti_rotation_feature} onChange={(v) => set('anti_rotation_feature', v)} /><TextInput label="Secondary retention" value={form.secondary_retention} onChange={(v) => set('secondary_retention', v)} /><TextInput label="Mechanical stop" value={form.mechanical_stop} onChange={(v) => set('mechanical_stop', v)} /><div className="sm:col-span-2 lg:col-span-3"><Toggle label="Flexible insert" checked={form.flexible_insert} onChange={(v) => set('flexible_insert', v)} /></div></Grid>;
}
function HardwareStep({ form, set }) {
  return <Grid><TextInput label="Main connector material" value={form.main_connector_material} onChange={(v) => set('main_connector_material', v)} /><TextInput label="Flexible insert material" value={form.flexible_insert_material} onChange={(v) => set('flexible_insert_material', v)} /><TextInput label="Fastener type" value={form.fastener_type} onChange={(v) => set('fastener_type', v)} /><TextInput label="Fastener size" value={form.fastener_size} onChange={(v) => set('fastener_size', v)} /><TextInput label="Washer type" value={form.washer_type} onChange={(v) => set('washer_type', v)} /><TextInput label="Thread type" value={form.thread_type} onChange={(v) => set('thread_type', v)} /><TextInput label="Hardware quantity" type="number" value={form.hardware_quantity} onChange={(v) => set('hardware_quantity', v)} /><TextInput label="Recommended print material" value={form.recommended_print_material} onChange={(v) => set('recommended_print_material', v)} /><TextInput label="Printer / nozzle profile" value={form.printer_profile} onChange={(v) => set('printer_profile', v)} /><TextInput label="Hardware notes" value={form.hardware_notes} onChange={(v) => set('hardware_notes', v)} full /></Grid>;
}
function ClearanceStep({ form, set }) {
  return <Grid><TextInput label="Installation clearance (mm)" type="number" value={form.required_installation_clearance_mm} onChange={(v) => set('required_installation_clearance_mm', v)} /><TextInput label="Cover clearance (mm)" type="number" value={form.required_cover_clearance_mm} onChange={(v) => set('required_cover_clearance_mm', v)} /><TextInput label="Emergency release clearance (mm)" type="number" value={form.emergency_release_clearance_mm} onChange={(v) => set('emergency_release_clearance_mm', v)} /><TextInput label="Fastener access" value={form.fastener_access} onChange={(v) => set('fastener_access', v)} /><TextInput label="Release access" value={form.release_access} onChange={(v) => set('release_access', v)} /><TextInput label="Hardware protrusion envelope" value={form.hardware_protrusion_envelope} onChange={(v) => set('hardware_protrusion_envelope', v)} /></Grid>;
}
function SafetyStep({ form, set }) {
  const items = [['safety_no_implant','No implant attachment'],['safety_no_abutment','No abutment attachment'],['safety_no_stoma','No stoma contact'],['safety_no_skin','No skin contact'],['safety_no_alignment','No alignment interference'],['safety_no_release','No release obstruction'],['safety_no_movement','No movement obstruction'],['safety_no_maintenance','No maintenance obstruction']];
  return <div className="space-y-2.5">{items.map(([k, label]) => <Toggle key={k} label={label} checked={form[k]} onChange={(v) => set(k, v)} />)}<div className="rounded-lg border border-amber-400/30 bg-amber-400/5 p-3 text-xs text-amber-200">All safety confirmations must be checked before approval.</div></div>;
}
function FilesStep({ form, set }) {
  return <Grid><FileField label="STEP file URL" value={form.step_file_url} onChange={(v) => set('step_file_url', v)} /><FileField label="STL file URL" value={form.stl_file_url} onChange={(v) => set('stl_file_url', v)} /><FileField label="3MF file URL" value={form.three_mf_file_url} onChange={(v) => set('three_mf_file_url', v)} /><FileField label="GLB preview URL" value={form.glb_preview_url} onChange={(v) => set('glb_preview_url', v)} /><FileField label="Technical drawing URL" value={form.technical_drawing_url} onChange={(v) => set('technical_drawing_url', v)} /><FileField label="Photograph URL" value={form.photograph_url} onChange={(v) => set('photograph_url', v)} /><FileField label="Assembly diagram URL" value={form.assembly_diagram_url} onChange={(v) => set('assembly_diagram_url', v)} /><FileField label="Validation report URL" value={form.validation_report_url} onChange={(v) => set('validation_report_url', v)} /><TextInput label="File checksum" value={form.file_checksum} onChange={(v) => set('file_checksum', v)} /></Grid>;
}
function FileField({ label, value, onChange }) { return <Field label={label}><div className="flex gap-2"><input className="workshop-input flex-1" value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder="Paste URL or upload" /><UploadBtn onUpload={onChange} /></div></Field>; }
function UploadBtn({ onUpload }) {
  const [busy, setBusy] = useState(false);
  const handle = async (e) => {
    const file = e.target.files?.[0]; if (!file) return;
    setBusy(true);
    try { const { file_url } = await base44.integrations.Core.UploadFile({ file }); onUpload(file_url); } catch (_) {}
    finally { setBusy(false); }
  };
  return <label className="btn-secondary cursor-pointer !px-3">{busy ? '…' : 'Upload'}<input type="file" className="hidden" onChange={handle} /></label>;
}
function ReviewStep({ form, validation }) {
  const dims = ['overall_width_mm','overall_depth_mm','overall_height_mm','attachment_point_count','attachment_point_coordinates'];
  const missing = dims.filter((d) => !form[d]);
  return <div className="space-y-4"><div className="grid gap-3 sm:grid-cols-2"><div className="rounded-lg border border-shire-border bg-shire-raised p-3"><div className="text-xs uppercase text-slate-500">Approval status</div><StatusPill tone="amber">{form.approval_status}</StatusPill></div><div className="rounded-lg border border-shire-border bg-shire-raised p-3"><div className="text-xs uppercase text-slate-500">Validation</div><StatusPill tone={validation.level === 'pass' ? 'green' : validation.level === 'blocked' ? 'red' : 'amber'}>{validation.status}</StatusPill></div></div>{missing.length > 0 && <div className="rounded-lg border border-amber-400/30 bg-amber-400/5 p-3 text-xs text-amber-200">Missing dimensions: {missing.join(', ')}</div>}{validation.issues.length > 0 && <div className="rounded-lg border border-shire-border bg-shire-raised p-3 text-xs text-slate-300"><div className="mb-1 font-medium text-slate-400">Validation issues:</div><ul className="space-y-1">{validation.issues.map((i, idx) => <li key={idx}>• {i}</li>)}</ul></div>}<div className="text-xs text-slate-500">Dimensions persist to the Ossiguard profile record. Revisions are preserved — old revisions are marked Superseded, never deleted. Do not claim approval until manually verified.</div></div>;
}