import { useState, useEffect } from 'react';
import { measurementService } from '@/services/measurementService';
import { ChevronLeft, ChevronRight, Save, SkipForward, Camera, AlertTriangle, CheckCircle2 } from 'lucide-react';

const VIEW_BY_CATEGORY = {
  Circumference: 'lateral',
  Width: 'top',
  Depth: 'top',
  Length: 'front',
  Height: 'front',
  General: 'perspective',
  'Knee component': 'lateral',
  'Lower leg': 'lateral',
  'Upper limb': 'lateral',
  Osseointegration: 'front',
};

export default function MeasurementStudio3D({ session, onGuidedView, onHighlightStation, onComplete, actor = 'Ray' }) {
  const [definitions, setDefinitions] = useState([]);
  const [index, setIndex] = useState(0);
  const [value, setValue] = useState('');
  const [enteredUnit, setEnteredUnit] = useState('mm');
  const [confidence, setConfidence] = useState('High');
  const [notes, setNotes] = useState('');
  const [saving, setSaving] = useState(false);
  const [warning, setWarning] = useState('');

  useEffect(() => {
    if (session?.workflow) {
      measurementService.definitions(session.workflow).then(defs => {
        setDefinitions(defs.filter(d => d.active !== false));
        setIndex(0);
        setValue('');
        setNotes('');
        setWarning('');
      });
    }
  }, [session?.uuid, session?.workflow]);

  const current = definitions[index];

  useEffect(() => {
    if (current) {
      const view = VIEW_BY_CATEGORY[current.category] || VIEW_BY_CATEGORY[current.workflow] || 'perspective';
      onGuidedView?.(view);
      onHighlightStation?.(index % 5);
    }
  }, [index, current]);

  if (!session) {
    return (
      <div className="flex h-full flex-col items-center justify-center p-8 text-center">
        <Camera className="mb-3 h-10 w-10 text-slate-600" />
        <p className="text-sm text-slate-400">No active measurement session.</p>
        <p className="mt-1 text-xs text-slate-500">Start a session from the Measurement Studio to begin guided 3D recording.</p>
      </div>
    );
  }

  if (!current) {
    return (
      <div className="flex h-full flex-col items-center justify-center p-8 text-center">
        <CheckCircle2 className="mb-3 h-10 w-10 text-emerald-400" />
        <p className="text-sm text-slate-300">All measurements complete.</p>
      </div>
    );
  }

  const handleSave = async () => {
    if (!value) return;
    setSaving(true);
    setWarning('');
    try {
      const saved = await measurementService.save(session, current, { value: Number(value), entered_unit: enteredUnit, confidence, notes, photo_url: '' }, actor);
      if (saved.warning) setWarning(saved.warning);
      setValue('');
      setNotes('');
      if (index < definitions.length - 1) {
        setIndex(index + 1);
      } else {
        await measurementService.progress(session, definitions.length, definitions.length);
        onComplete?.();
      }
    } catch (e) {
      setWarning('Save failed: ' + e.message);
    }
    setSaving(false);
  };

  const handleSkip = async () => {
    setSaving(true);
    try {
      await measurementService.skip(session, current, 'Not applicable for this limb', actor);
      if (index < definitions.length - 1) setIndex(index + 1);
      else onComplete?.();
    } catch (e) { setWarning('Skip failed'); }
    setSaving(false);
  };

  const progress = definitions.length ? Math.round((index / definitions.length) * 100) : 0;

  return (
    <div className="flex h-full flex-col">
      <div className="border-b border-white/10 px-4 py-3">
        <h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-cyan-400">Guided 3D Measurement</h2>
        <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-white/10">
          <div className="h-full rounded-full bg-cyan-400 transition-all" style={{ width: `${progress}%` }} />
        </div>
        <p className="mt-1.5 text-xs text-slate-500">Measurement {index + 1} of {definitions.length} • {progress}%</p>
      </div>
      <div className="flex-1 overflow-y-auto p-4">
        <div className="mb-3 flex items-center gap-2">
          <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-400/15 text-sm font-bold text-cyan-300">{index + 1}</span>
          <h3 className="text-lg font-semibold text-white">{current.name}</h3>
        </div>
        {current.required_tool && (
          <div className="mb-3 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-400">
            <span className="font-semibold text-slate-300">Required tool:</span> {current.required_tool}
          </div>
        )}
        <p className="mb-4 text-sm leading-6 text-slate-300">{current.explanation}</p>
        <div className="mb-3 rounded-lg border border-cyan-400/20 bg-cyan-400/5 px-3 py-2 text-xs text-cyan-300">
          <Camera className="mr-1.5 inline h-3.5 w-3.5" />
          Auto-rotating to: <span className="font-semibold capitalize">{VIEW_BY_CATEGORY[current.category] || 'perspective'}</span> view
        </div>
        <div className="space-y-3">
          <div>
            <label className="text-xs font-medium text-slate-400">Value</label>
            <div className="flex gap-2">
              <input type="number" value={value} onChange={e => setValue(e.target.value)} placeholder="Enter measurement" className="workshop-input flex-1" />
              <select value={enteredUnit} onChange={e => setEnteredUnit(e.target.value)} className="workshop-input w-20">
                <option value="mm">mm</option>
                <option value="cm">cm</option>
                <option value="degrees">°</option>
              </select>
            </div>
          </div>
          <div>
            <label className="text-xs font-medium text-slate-400">Confidence</label>
            <select value={confidence} onChange={e => setConfidence(e.target.value)} className="workshop-input">
              <option value="High">High</option>
              <option value="Medium">Medium</option>
              <option value="Low">Low</option>
            </select>
          </div>
          <div>
            <label className="text-xs font-medium text-slate-400">Notes</label>
            <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="Optional notes..." className="workshop-input min-h-16" />
          </div>
          {warning && (
            <div className="flex items-start gap-2 rounded-lg border border-amber-400/30 bg-amber-400/10 px-3 py-2 text-xs text-amber-300">
              <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />{warning}
            </div>
          )}
        </div>
      </div>
      <div className="flex items-center gap-2 border-t border-white/10 p-3">
        <button onClick={() => setIndex(Math.max(0, index - 1))} disabled={index === 0} className="btn-secondary !px-3"><ChevronLeft className="h-4 w-4" /></button>
        <button onClick={handleSkip} disabled={saving} className="btn-secondary flex-1"><SkipForward className="h-4 w-4" />Skip</button>
        <button onClick={handleSave} disabled={saving || !value} className="btn-primary flex-1"><Save className="h-4 w-4" />{saving ? 'Saving...' : 'Save & Next'}<ChevronRight className="h-4 w-4" /></button>
      </div>
    </div>
  );
}