import { useState } from 'react';
import { Ruler, Save, RotateCw, Ban, Camera, ChevronDown, CheckCircle2, ArrowUpRight } from 'lucide-react';
import StatusPill from '@/components/workshop/StatusPill';

const SOURCES = ['Manufacturer Verified', 'Workshop Measurement', 'Verified 3D Scan', 'Customer Reported', 'Calculated', 'Estimated', 'Unknown'];
const VERIFICATIONS = ['Unknown', 'Requested', 'Entered', 'Needs Verification', 'Verified Manufacturer Value', 'Verified Workshop Value', 'Verified Scan Value', 'Conflict Detected', 'Superseded', 'Not Applicable'];

function InspectorField({ label, children }) {
  return (
    <div className="border-b border-white/5 py-2.5">
      <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-[0.1em] text-slate-500">{label}</label>
      {children}
    </div>
  );
}

export default function MeasurementInspector({ selected, component, stationIndex, onSave, onMeasureAgain, onNotApplicable, previousValue, onAddPhoto }) {
  const s = selected?.data || {};
  const name = s.name || s.station_name || (stationIndex != null ? `Station ${String(stationIndex + 1).padStart(2, '0')}` : 'Measurement');
  const width = s.width ?? s.total_width_mm;
  const depth = s.depth ?? s.total_depth_mm;
  const height = s.height ?? s.height_from_origin_mm;

  const [value, setValue] = useState('');
  const [unit, setUnit] = useState('mm');
  const [source, setSource] = useState(SOURCES[1]);
  const [verification, setVerification] = useState(VERIFICATIONS[2]);
  const [confidence, setConfidence] = useState(95);
  const [notes, setNotes] = useState('');

  const diff = previousValue && value ? (Number(value) - previousValue).toFixed(1) : null;

  const save = () => onSave?.({ selected, value, unit, source, verification, confidence, notes });

  return (
    <div className="flex h-full flex-col">
      {/* Header dropdown */}
      <div className="border-b border-white/10 px-4 py-3">
        <div className="flex items-center justify-between">
          <h2 className="flex items-center gap-2 text-sm font-bold uppercase tracking-[0.12em] text-cyan-300">
            <Ruler className="h-4 w-4" />
            {stationIndex != null ? `Measurement Station ${String(stationIndex + 1).padStart(2, '0')}` : 'Measurement'}
          </h2>
          <button className="flex items-center gap-1 text-xs text-slate-400 hover:text-cyan-300">
            {name} <ChevronDown className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-4">
        <div className="mb-1 text-xs font-semibold uppercase tracking-[0.1em] text-slate-500">Measurement Name</div>
        <p className="mb-3 text-sm font-semibold text-white">{name}</p>

        <InspectorField label="Value">
          <div className="flex gap-2">
            <input type="number" value={value} onChange={(e) => setValue(e.target.value)} placeholder="Measurement required — enter value" className="workshop-input flex-1 !min-h-10" />
            <select value={unit} onChange={(e) => setUnit(e.target.value)} className="workshop-input w-20 !min-h-10">
              <option value="mm">mm</option>
              <option value="cm">cm</option>
              <option value="degrees">°</option>
            </select>
          </div>
        </InspectorField>

        {width != null && (
          <div className="flex items-baseline justify-between py-2 text-sm">
            <span className="text-slate-400">Width × Depth</span>
            <span className="font-semibold text-slate-100">{width.toFixed ? width.toFixed(0) : width} × {depth?.toFixed ? depth.toFixed(0) : depth} mm</span>
          </div>
        )}

        <InspectorField label="Source">
          <select value={source} onChange={(e) => setSource(e.target.value)} className="workshop-input !min-h-10">
            {SOURCES.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        </InspectorField>

        <InspectorField label="Verification">
          <div className="flex items-center gap-2">
            <select value={verification} onChange={(e) => setVerification(e.target.value)} className="workshop-input flex-1 !min-h-10">
              {VERIFICATIONS.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
            <StatusPill tone="green"><CheckCircle2 className="mr-1 h-3 w-3" />Verified</StatusPill>
          </div>
        </InspectorField>

        <InspectorField label="Confidence">
          <div className="flex items-center gap-2">
            <input type="range" min={0} max={100} value={confidence} onChange={(e) => setConfidence(parseInt(e.target.value))} className="flex-1 accent-cyan-400" />
            <span className="w-16 text-right text-sm font-semibold text-cyan-300">High ({confidence}%)</span>
          </div>
        </InspectorField>

        <InspectorField label="Notes">
          <textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Add notes…" className="workshop-input min-h-16 !min-h-12" />
        </InspectorField>

        {previousValue != null && (
          <div className="mt-3 flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.02] px-3 py-2.5">
            <span className="text-xs text-slate-500">Previous value</span>
            <span className="text-sm font-semibold text-slate-200">
              {previousValue.toFixed ? previousValue.toFixed(1) : previousValue} mm
              {diff && Number(diff) !== 0 && (
                <span className={`ml-2 inline-flex items-center text-xs ${Number(diff) > 0 ? 'text-amber-300' : 'text-emerald-300'}`}>
                  {Number(diff) > 0 ? '+' : ''}{diff} mm <ArrowUpRight className="ml-0.5 h-3 w-3" />
                </span>
              )}
            </span>
          </div>
        )}
      </div>

      <div className="border-t border-white/10 p-3">
        <div className="grid grid-cols-2 gap-2">
          <button className="btn-secondary !min-h-10" onClick={onMeasureAgain}><RotateCw className="h-4 w-4" />Measure Again</button>
          <button className="btn-secondary !min-h-10" onClick={onNotApplicable}><Ban className="h-4 w-4" />N/A</button>
        </div>
        <button className="btn-primary mt-2 w-full" onClick={save} disabled={!value}>
          <Camera className="h-4 w-4" />Add Photo
        </button>
        <button className="btn-primary mt-2 w-full !min-h-12" onClick={save} disabled={!value}>
          <Save className="h-4 w-4" />Save &amp; Continue
        </button>
      </div>
    </div>
  );
}