import { useState } from 'react';
import { Upload, ShieldCheck } from 'lucide-react';
import { ossiguardService, OSSIGUARD_APPROVAL_STATUSES, OSSIGUARD_GEOMETRY_STATUSES, OSSIGUARD_RETENTION_METHODS, OSSIGUARD_COVER_INTERFACES, SAFETY_BANNER } from '@/services/ossiguardService';
import { adapters } from '@/services/serviceConfig';

function Field({ label, children }) {
  return <div><label className="text-xs font-medium text-slate-400">{label}</label>{children}</div>;
}

function TextInput({ label, value, onChange, placeholder }) {
  return <Field label={label}><input className="workshop-input" value={value || ''} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} /></Field>;
}

function NumberInput({ label, value, onChange, placeholder }) {
  return <Field label={label}><input type="number" className="workshop-input" value={value ?? ''} placeholder={placeholder} onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)} /></Field>;
}

function Select({ label, value, onChange, options }) {
  return <Field label={label}><select className="workshop-input" value={value || ''} onChange={(e) => onChange(e.target.value)}><option value="">—</option>{options.map((o) => <option key={o} value={o}>{o}</option>)}</select></Field>;
}

function FileUpload({ label, value, onChange, accept }) {
  const [uploading, setUploading] = useState(false);
  const handle = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setUploading(true);
    try {
      const result = await adapters.files.upload(file, `/SHiREVault/SHiRELimbs/Components/Ossiguard`);
      onChange(result.location);
    } catch (_) { /* ignore */ }
    setUploading(false);
  };
  return <Field label={label}><div className="flex items-center gap-2"><label className="btn-secondary cursor-pointer !py-1.5 text-xs"><Upload className="h-3.5 w-3.5" />{uploading ? 'Uploading…' : 'Upload'}<input type="file" accept={accept} className="hidden" onChange={handle} /></label>{value && <span className="text-xs text-emerald-300">Attached</span>}</div></Field>;
}

export default function OssiguardProfileForm({ initial, onSave, onCancel }) {
  const [form, setForm] = useState(initial || {});
  const set = (key) => (val) => setForm((f) => ({ ...f, [key]: val }));

  return (
    <form onSubmit={(e) => { e.preventDefault(); onSave(form); }} className="space-y-6">
      <div className="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>

      <section>
        <h3 className="section-title">Identification</h3>
        <div className="grid gap-4 sm:grid-cols-2">
          <TextInput label="Profile name *" value={form.profile_name} onChange={set('profile_name')} placeholder="e.g. Ossiguard Standard" />
          <TextInput label="Version *" value={form.version} onChange={set('version')} placeholder="e.g. v1" />
          <NumberInput label="Connector revision" value={form.connector_revision} onChange={set('connector_revision')} />
          <TextInput label="Designed by" value={form.designed_by} onChange={set('designed_by')} />
          <TextInput label="Date created" value={form.date_created} onChange={set('date_created')} placeholder="YYYY-MM-DD" />
          <TextInput label="Date approved" value={form.date_approved} onChange={set('date_approved')} placeholder="YYYY-MM-DD" />
          <Select label="Approval status" value={form.approval_status} onChange={set('approval_status')} options={OSSIGUARD_APPROVAL_STATUSES} />
          <Select label="Geometry status" value={form.geometry_status} onChange={set('geometry_status')} options={OSSIGUARD_GEOMETRY_STATUSES} />
          <TextInput label="Compatible limb type" value={form.compatible_limb_type} onChange={set('compatible_limb_type')} />
          <TextInput label="Compatible prosthesis type" value={form.compatible_prosthesis_type} onChange={set('compatible_prosthesis_type')} />
          <TextInput label="Compatible component models" value={form.compatible_component_models} onChange={set('compatible_component_models')} />
          <TextInput label="Customer UUID (optional)" value={form.customer_uuid} onChange={set('customer_uuid')} />
        </div>
      </section>

      <section>
        <h3 className="section-title">Interface — what it attaches to</h3>
        <div className="grid gap-4 sm:grid-cols-2">
          <TextInput label="Attaches to component UUID" value={form.attaches_to_component_uuid} onChange={set('attaches_to_component_uuid')} />
          <TextInput label="Attaches to component label" value={form.attaches_to_component_label} onChange={set('attaches_to_component_label')} placeholder="e.g. Össur Pylon 30mm" />
          <TextInput label="Approved contact surfaces" value={form.approved_contact_surfaces} onChange={set('approved_contact_surfaces')} />
          <TextInput label="Prohibited contact surfaces" value={form.prohibited_contact_surfaces} onChange={set('prohibited_contact_surfaces')} />
          <Select label="Retention method" value={form.retention_method} onChange={set('retention_method')} options={OSSIGUARD_RETENTION_METHODS} />
          <TextInput label="Release method" value={form.release_method} onChange={set('release_method')} />
          <TextInput label="Alignment features" value={form.alignment_features} onChange={set('alignment_features')} />
          <TextInput label="Anti-rotation feature" value={form.anti_rotation_feature} onChange={set('anti_rotation_feature')} />
          <Select label="Cover-side interface" value={form.cover_side_interface} onChange={set('cover_side_interface')} options={OSSIGUARD_COVER_INTERFACES} />
          <TextInput label="Prosthesis-side interface" value={form.prosthesis_side_interface} onChange={set('prosthesis_side_interface')} />
          <label className="choice-card"><input type="checkbox" checked={!!form.replaceable_insert} onChange={(e) => set('replaceable_insert')(e.target.checked)} />Replaceable insert</label>
          <label className="choice-card"><input type="checkbox" checked={!!form.flexible_insert} onChange={(e) => set('flexible_insert')(e.target.checked)} />Flexible insert</label>
          <TextInput label="Protective padding" value={form.protective_padding} onChange={set('protective_padding')} />
          <TextInput label="Mechanical stop" value={form.mechanical_stop} onChange={set('mechanical_stop')} />
          <TextInput label="Secondary retention" value={form.secondary_retention} onChange={set('secondary_retention')} />
        </div>
      </section>

      <section>
        <h3 className="section-title">Geometry — exact dimensions</h3>
        <div className="grid gap-4 sm:grid-cols-3">
          <NumberInput label="Overall width (mm)" value={form.overall_width_mm} onChange={set('overall_width_mm')} />
          <NumberInput label="Overall depth (mm)" value={form.overall_depth_mm} onChange={set('overall_depth_mm')} />
          <NumberInput label="Overall height (mm)" value={form.overall_height_mm} onChange={set('overall_height_mm')} />
          <TextInput label="Mount centre position" value={form.mount_centre_position} onChange={set('mount_centre_position')} />
          <TextInput label="Mounting-axis direction" value={form.mounting_axis_direction} onChange={set('mounting_axis_direction')} />
          <NumberInput label="Proximal position (mm)" value={form.proximal_position_mm} onChange={set('proximal_position_mm')} />
          <NumberInput label="Distal position (mm)" value={form.distal_position_mm} onChange={set('distal_position_mm')} />
          <NumberInput label="Medial offset (mm)" value={form.medial_offset_mm} onChange={set('medial_offset_mm')} />
          <NumberInput label="Lateral offset (mm)" value={form.lateral_offset_mm} onChange={set('lateral_offset_mm')} />
          <NumberInput label="Anterior offset (mm)" value={form.anterior_offset_mm} onChange={set('anterior_offset_mm')} />
          <NumberInput label="Posterior offset (mm)" value={form.posterior_offset_mm} onChange={set('posterior_offset_mm')} />
          <NumberInput label="Rotation (degrees)" value={form.rotation_degrees} onChange={set('rotation_degrees')} />
          <NumberInput label="Attachment point count" value={form.attachment_point_count} onChange={set('attachment_point_count')} />
          <TextInput label="Attachment point coordinates" value={form.attachment_point_coordinates} onChange={set('attachment_point_coordinates')} />
          <NumberInput label="Fastener spacing (mm)" value={form.fastener_spacing_mm} onChange={set('fastener_spacing_mm')} />
          <TextInput label="Hole diameters (mm)" value={form.hole_diameters_mm} onChange={set('hole_diameters_mm')} />
          <TextInput label="Clip dimensions" value={form.clip_dimensions} onChange={set('clip_dimensions')} />
          <TextInput label="Receiver dimensions" value={form.receiver_dimensions} onChange={set('receiver_dimensions')} />
          <TextInput label="Insertion direction" value={form.insertion_direction} onChange={set('insertion_direction')} />
          <TextInput label="Removal direction" value={form.removal_direction} onChange={set('removal_direction')} />
          <NumberInput label="Installation clearance (mm)" value={form.required_installation_clearance_mm} onChange={set('required_installation_clearance_mm')} />
          <NumberInput label="Cover clearance (mm)" value={form.required_cover_clearance_mm} onChange={set('required_cover_clearance_mm')} />
          <TextInput label="Hardware protrusion envelope" value={form.hardware_protrusion_envelope} onChange={set('hardware_protrusion_envelope')} />
          <NumberInput label="Emergency-release clearance (mm)" value={form.emergency_release_clearance_mm} onChange={set('emergency_release_clearance_mm')} />
        </div>
      </section>

      <section>
        <h3 className="section-title">Materials &amp; hardware</h3>
        <div className="grid gap-4 sm:grid-cols-2">
          <TextInput label="Main connector material" value={form.main_connector_material} onChange={set('main_connector_material')} />
          <TextInput label="Flexible insert material" value={form.flexible_insert_material} onChange={set('flexible_insert_material')} />
          <TextInput label="Fastener type" value={form.fastener_type} onChange={set('fastener_type')} />
          <TextInput label="Fastener size" value={form.fastener_size} onChange={set('fastener_size')} />
          <TextInput label="Washer type" value={form.washer_type} onChange={set('washer_type')} />
          <TextInput label="Thread type" value={form.thread_type} onChange={set('thread_type')} />
          <NumberInput label="Hardware quantity" value={form.hardware_quantity} onChange={set('hardware_quantity')} />
          <TextInput label="Recommended print material" value={form.recommended_print_material} onChange={set('recommended_print_material')} />
          <TextInput label="Printer profile" value={form.printer_profile} onChange={set('printer_profile')} />
          <TextInput label="Hardware notes" value={form.hardware_notes} onChange={set('hardware_notes')} />
        </div>
      </section>

      <section>
        <h3 className="section-title">Design files &amp; CAD</h3>
        <div className="grid gap-4 sm:grid-cols-2">
          <FileUpload label="STEP file" value={form.step_file_url} onChange={set('step_file_url')} accept=".step,.stp" />
          <FileUpload label="STL file" value={form.stl_file_url} onChange={set('stl_file_url')} accept=".stl" />
          <FileUpload label="3MF file" value={form.three_mf_file_url} onChange={set('three_mf_file_url')} accept=".3mf" />
          <FileUpload label="GLB preview" value={form.glb_preview_url} onChange={set('glb_preview_url')} accept=".glb,.gltf" />
          <FileUpload label="Technical drawing (PDF)" value={form.technical_drawing_url} onChange={set('technical_drawing_url')} accept=".pdf" />
          <FileUpload label="Assembly diagram" value={form.assembly_diagram_url} onChange={set('assembly_diagram_url')} accept=".pdf,.png,.jpg" />
          <FileUpload label="Photograph" value={form.photograph_url} onChange={set('photograph_url')} accept="image/*" />
          <FileUpload label="Validation report" value={form.validation_report_url} onChange={set('validation_report_url')} accept=".pdf" />
          <TextInput label="File checksum" value={form.file_checksum} onChange={set('file_checksum')} />
        </div>
        <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>
        <h3 className="section-title">Keep-out zones &amp; notes</h3>
        <div className="grid gap-4">
          <Field label="Keep-out zones (descriptive)"><textarea className="workshop-input min-h-20" value={form.keep_out_zones || ''} onChange={(e) => set('keep_out_zones')(e.target.value)} /></Field>
          <Field label="Missing dimensions"><textarea className="workshop-input min-h-16" value={form.missing_dimensions || ''} onChange={(e) => set('missing_dimensions')(e.target.value)} /></Field>
          <Field label="Revision notes"><textarea className="workshop-input min-h-16" value={form.revision_notes || ''} onChange={(e) => set('revision_notes')(e.target.value)} /></Field>
          <Field label="Notes"><textarea className="workshop-input min-h-16" value={form.notes || ''} onChange={(e) => set('notes')(e.target.value)} /></Field>
        </div>
      </section>

      <div className="flex gap-2">
        <button type="submit" className="btn-primary">Save Ossiguard Profile</button>
        <button type="button" onClick={onCancel} className="btn-secondary">Cancel</button>
      </div>
    </form>
  );
}