import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { ArrowLeft, Copy, GitCompare, History, ShieldCheck } 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 LoadingPanel from '@/components/workshop/LoadingPanel';
import OssiguardProfileForm from '@/components/ossiguard/OssiguardProfileForm';
import OssiguardValidation from '@/components/ossiguard/OssiguardValidation';
import { ossiguardService, SAFETY_BANNER } from '@/services/ossiguardService';

export default function OssiguardDetail() {
  const { uuid } = useParams();
  const [profile, setProfile] = useState(null);
  const [revisions, setRevisions] = useState([]);
  const [editing, setEditing] = useState(false);
  const [loading, setLoading] = useState(true);

  const load = async () => {
    const p = await ossiguardService.get(uuid);
    setProfile(p);
    if (p) setRevisions(await ossiguardService.listRevisions(p.profile_name));
    setLoading(false);
  };
  useEffect(() => { load(); }, [uuid]);

  const save = async (f) => {
    await ossiguardService.update(profile, f, 'Ray');
    setEditing(false);
    load();
  };

  const newRevision = async () => {
    await ossiguardService.newRevision(uuid, { ...profile, revision_notes: `New revision from rev${profile.connector_revision}` }, 'Ray');
    load();
  };

  if (loading) return <LoadingPanel label="Loading Ossiguard profile" />;
  if (!profile) return <div className="panel mx-auto mt-10 max-w-lg p-8 text-center"><h1 className="text-xl font-semibold text-white">Profile not found</h1><Link className="btn-secondary mt-4" to="/ossiguard">Back to library</Link></div>;

  return (
    <>
      <Breadcrumbs items={[{ label: 'Ossiguard Library', to: '/ossiguard' }, { label: `${profile.profile_name} rev${profile.connector_revision}` }]} />
      <PageHeader
        eyebrow={`${profile.version} · rev${profile.connector_revision}`}
        title={profile.profile_name}
        description={profile.data_label || 'SHiRE Ossiguard connector profile'}
        action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to="/ossiguard"><ArrowLeft className="h-4 w-4" />Back</Link><button onClick={newRevision} className="btn-secondary"><Copy className="h-4 w-4" />New Revision</button><button onClick={() => setEditing(true)} className="btn-primary">Edit Profile</button></div>}
      />

      <div className="mb-4 flex flex-wrap items-center gap-2">
        <StatusPill tone={profile.approval_status === 'Approved Connector Revision' ? 'green' : profile.approval_status === 'Superseded' ? 'slate' : 'amber'}>{profile.approval_status}</StatusPill>
        <StatusPill tone="cyan">{profile.geometry_status}</StatusPill>
        {profile.customer_uuid && <StatusPill tone="slate">Customer-linked</StatusPill>}
      </div>

      <div className="mb-5 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>

      {editing ? (
        <div className="panel mb-6 p-6">
          <h2 className="section-title">Edit Ossiguard Profile</h2>
          <OssiguardProfileForm initial={profile} onSave={save} onCancel={() => setEditing(false)} />
        </div>
      ) : (
        <div className="space-y-5">
          <section className="panel p-5">
            <h2 className="section-title">Identification</h2>
            <FieldList rows={[
              ['Profile name', profile.profile_name],
              ['Version', profile.version],
              ['Revision', `rev${profile.connector_revision}`],
              ['Designed by', profile.designed_by],
              ['Date created', profile.date_created],
              ['Date approved', profile.date_approved],
              ['Compatible limb type', profile.compatible_limb_type],
              ['Compatible prosthesis type', profile.compatible_prosthesis_type],
              ['Compatible component models', profile.compatible_component_models],
            ]} />
          </section>

          <section className="panel p-5">
            <h2 className="section-title">Interface</h2>
            <FieldList columns={1} rows={[
              ['Attaches to component', profile.attaches_to_component_label],
              ['Approved contact surfaces', profile.approved_contact_surfaces],
              ['Prohibited contact surfaces', profile.prohibited_contact_surfaces],
              ['Retention method', profile.retention_method],
              ['Release method', profile.release_method],
              ['Alignment features', profile.alignment_features],
              ['Anti-rotation feature', profile.anti_rotation_feature],
              ['Cover-side interface', profile.cover_side_interface],
              ['Prosthesis-side interface', profile.prosthesis_side_interface],
              ['Replaceable insert', profile.replaceable_insert ? 'Yes' : 'No'],
              ['Flexible insert', profile.flexible_insert ? 'Yes' : 'No'],
              ['Protective padding', profile.protective_padding],
              ['Mechanical stop', profile.mechanical_stop],
              ['Secondary retention', profile.secondary_retention],
            ]} />
          </section>

          <section className="panel p-5">
            <h2 className="section-title">Geometry — Exact Dimensions</h2>
            <FieldList rows={[
              ['Overall width', profile.overall_width_mm ? `${profile.overall_width_mm} mm` : null],
              ['Overall depth', profile.overall_depth_mm ? `${profile.overall_depth_mm} mm` : null],
              ['Overall height', profile.overall_height_mm ? `${profile.overall_height_mm} mm` : null],
              ['Mount centre position', profile.mount_centre_position],
              ['Mounting-axis direction', profile.mounting_axis_direction],
              ['Proximal position', profile.proximal_position_mm ? `${profile.proximal_position_mm} mm` : null],
              ['Distal position', profile.distal_position_mm ? `${profile.distal_position_mm} mm` : null],
              ['Medial offset', profile.medial_offset_mm ? `${profile.medial_offset_mm} mm` : null],
              ['Lateral offset', profile.lateral_offset_mm ? `${profile.lateral_offset_mm} mm` : null],
              ['Anterior offset', profile.anterior_offset_mm ? `${profile.anterior_offset_mm} mm` : null],
              ['Posterior offset', profile.posterior_offset_mm ? `${profile.posterior_offset_mm} mm` : null],
              ['Rotation', profile.rotation_degrees ? `${profile.rotation_degrees}°` : null],
              ['Attachment point count', profile.attachment_point_count],
              ['Attachment point coordinates', profile.attachment_point_coordinates],
              ['Fastener spacing', profile.fastener_spacing_mm ? `${profile.fastener_spacing_mm} mm` : null],
              ['Hole diameters', profile.hole_diameters_mm],
              ['Clip dimensions', profile.clip_dimensions],
              ['Receiver dimensions', profile.receiver_dimensions],
              ['Insertion direction', profile.insertion_direction],
              ['Removal direction', profile.removal_direction],
              ['Installation clearance', profile.required_installation_clearance_mm ? `${profile.required_installation_clearance_mm} mm` : null],
              ['Cover clearance', profile.required_cover_clearance_mm ? `${profile.required_cover_clearance_mm} mm` : null],
              ['Hardware protrusion envelope', profile.hardware_protrusion_envelope],
              ['Emergency-release clearance', profile.emergency_release_clearance_mm ? `${profile.emergency_release_clearance_mm} mm` : null],
            ]} />
          </section>

          <section className="panel p-5">
            <h2 className="section-title">Materials &amp; Hardware</h2>
            <FieldList rows={[
              ['Main connector material', profile.main_connector_material],
              ['Flexible insert material', profile.flexible_insert_material],
              ['Fastener type', profile.fastener_type],
              ['Fastener size', profile.fastener_size],
              ['Washer type', profile.washer_type],
              ['Thread type', profile.thread_type],
              ['Hardware quantity', profile.hardware_quantity],
              ['Recommended print material', profile.recommended_print_material],
              ['Printer profile', profile.printer_profile],
              ['Hardware notes', profile.hardware_notes],
            ]} />
          </section>

          <section className="panel p-5">
            <h2 className="section-title">Design Files &amp; CAD</h2>
            <FieldList rows={[
              ['STEP file', profile.step_file_url ? 'Attached' : 'Not attached'],
              ['STL file', profile.stl_file_url ? 'Attached' : 'Not attached'],
              ['3MF file', profile.three_mf_file_url ? 'Attached' : 'Not attached'],
              ['GLB preview', profile.glb_preview_url ? 'Attached' : 'Not attached'],
              ['Technical drawing', profile.technical_drawing_url ? 'Attached' : 'Not attached'],
              ['Assembly diagram', profile.assembly_diagram_url ? 'Attached' : 'Not attached'],
              ['Photograph', profile.photograph_url ? 'Attached' : 'Not attached'],
              ['Validation report', profile.validation_report_url ? 'Attached' : 'Not attached'],
              ['File checksum', profile.file_checksum],
            ]} />
            <p className="mt-2 text-xs text-slate-500">Do not claim an Ossiguard profile is approved until dimensions and compatibility are manually verified.</p>
          </section>

          <section className="panel p-5">
            <h2 className="section-title">Validation</h2>
            <OssiguardValidation profile={profile} project={null} limb={null} />
          </section>

          <section className="panel p-5">
            <h2 className="section-title"><History className="mr-1.5 inline h-4 w-4" />Revision History</h2>
            {revisions.length > 1 ? (
              <ol className="space-y-2 text-sm">
                {revisions.map((r) => (
                  <li key={r.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">rev{r.connector_revision}</span>
                      <span className="ml-2 text-xs text-slate-500">{r.approval_status} · {r.date_created || r.created_date?.slice(0, 10)}</span>
                    </div>
                    {r.uuid !== uuid && <Link className="text-xs text-violet-300 hover:text-violet-200" to={`/ossiguard/${r.uuid}`}>View →</Link>}
                  </li>
                ))}
              </ol>
            ) : <p className="text-sm text-slate-500">Single revision — no prior versions.</p>}
          </section>

          {(profile.keep_out_zones || profile.missing_dimensions || profile.revision_notes || profile.notes) && (
            <section className="panel p-5">
              <h2 className="section-title">Notes &amp; Keep-Out Zones</h2>
              <FieldList columns={1} rows={[
                ['Keep-out zones', profile.keep_out_zones],
                ['Missing dimensions', profile.missing_dimensions],
                ['Revision notes', profile.revision_notes],
                ['Notes', profile.notes],
              ]} />
            </section>
          )}
        </div>
      )}
    </>
  );
}