import { useEffect, useState } from 'react';
import { ChevronLeft, RotateCcw, Pause, ExternalLink } from 'lucide-react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import MeasurementGuide from '@/components/measurements/MeasurementGuide';
import MeasurementEntry from '@/components/measurements/MeasurementEntry';
import BoundaryNotice from '@/components/workshop/BoundaryNotice';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { measurementService } from '@/services/measurementService';
import { componentService } from '@/services/componentService';
import { dimensionService } from '@/services/dimensionService';
import { dimensionAnalysis } from '@/services/dimensionAnalysis';
import { fileStorageService } from '@/services/fileStorageService';

const today = () => new Date().toISOString().slice(0, 10);

export default function MeasurementSession() {
  const { uuid } = useParams();
  const navigate = useNavigate();
  const [session, setSession] = useState();
  const [component, setComponent] = useState();
  const [tasks, setTasks] = useState([]);
  const [values, setValues] = useState([]);
  const [index, setIndex] = useState(0);
  const [busy, setBusy] = useState(false);

  const load = async () => {
    const s = await measurementService.session(uuid);
    if (s.component_uuid) {
      const comp = await componentService.get(s.component_uuid);
      const workflowTasks = await dimensionAnalysis.buildWorkflow(comp);
      const dims = await dimensionService.dimensions(s.component_uuid);
      const sessionDims = dims.filter(d => d.session_uuid === uuid);
      const done = new Set(sessionDims.map(d => d.dimension_key));
      const [specs, moves, access, keepouts] = await Promise.all([dimensionService.specs(s.component_uuid), dimensionService.movementPositions(s.component_uuid), dimensionService.accessPoints(s.component_uuid), dimensionService.keepOutZones(s.component_uuid)]);
      const specialDone = { _spec_import: specs.length > 0, _movement: moves.length > 0, _access: access.length > 0, _keepout: keepouts.length > 0 };
      const firstUndone = workflowTasks.findIndex(t => t.key.startsWith('_') ? !specialDone[t.key] : !done.has(t.key));
      setSession(s); setComponent(comp); setTasks(workflowTasks); setValues(sessionDims);
      setIndex(firstUndone < 0 ? workflowTasks.length : firstUndone);
    } else {
      const [d, v] = await Promise.all([measurementService.definitions(s.workflow), measurementService.values(uuid)]);
      setSession(s); setTasks(d); setValues(v);
      const done = new Set(v.map(x => x.definition_uuid));
      const firstUndone = d.findIndex(x => !done.has(x.uuid));
      setIndex(firstUndone < 0 ? d.length : firstUndone);
    }
  };

  useEffect(() => { load(); }, [uuid]);
  if (!session) return <LoadingPanel />;
  const isComponent = !!session.component_uuid;
  const advance = async (newIndex) => { const next = newIndex ?? (index + 1); setIndex(next); const total = tasks.length; const complete = Math.min(next, total); await measurementService.progress(session, complete, total); if (next >= total) load(); };
  const save = async (data) => {
    setBusy(true);
    try {
      let photoUrl = '', storageDest = '';
      if (data.photo) { const stored = await fileStorageService.uploadMeasurementPhoto(data.photo, session.project_uuid || session.component_uuid); photoUrl = stored.location; storageDest = stored.destination; }
      if (isComponent && !tasks[index].key.startsWith('_')) {
        const task = tasks[index];
        const value_mm = data.entered_unit === 'cm' ? Number(data.value) * 10 : Number(data.value);
        await dimensionService.saveDimension({ component_uuid: session.component_uuid, dimension_key: task.key, dimension_name: task.name, category: 'External envelope', source: 'Workshop Physical Measurement', value_mm, original_value: Number(data.value), original_unit: data.entered_unit, entered_unit: data.entered_unit, confidence: data.confidence, verification_status: 'Verified workshop value', entered_by: 'Ray', date_entered: today(), session_uuid: uuid, notes: data.notes, photo_url: photoUrl, storage_destination: storageDest }, 'Ray');
      } else if (!isComponent) {
        await measurementService.save(session, tasks[index], data, 'Ray');
      }
      await advance();
    } finally { setBusy(false); load(); }
  };
  const skip = async (reason) => { setBusy(true); if (!isComponent) await measurementService.skip(session, tasks[index], reason, 'Ray'); await advance(); setBusy(false); load(); };
  const pause = async () => { await measurementService.pause(session); navigate('/measurements'); };

  if (!tasks.length || index >= tasks.length) return (
    <div className="mx-auto max-w-2xl"><BoundaryNotice /><div className="panel mt-6 p-8 text-center"><p className="text-violet-400">MEASUREMENT SET COMPLETE</p><h1 className="mt-2 text-3xl font-semibold text-white">Ready for manual review</h1><p className="mt-3 text-slate-400">{values.filter(v => v.warning).length} saved warning(s) require review.</p><div className="mt-6 flex justify-center gap-3"><button onClick={() => setIndex(0)} className="btn-secondary"><RotateCcw />Review again</button>{isComponent && <Link to={`/components/${session.component_uuid}/dimensions`} className="btn-primary">Open component dimensions<ExternalLink /></Link>}</div></div></div>
  );

  const task = tasks[index];
  const isSpecial = isComponent && task.key && task.key.startsWith('_');
  const guideDef = isComponent ? { name: task.name, explanation: task.explanation, required_tool: 'Workshop calipers / measuring tape' } : task;

  return (
    <>
      <div className="mb-5 flex items-center justify-between">
        <Link to="/measurements" className="btn-secondary"><ChevronLeft />Back</Link>
        <div className="flex items-center gap-3"><StatusPill tone="cyan">{index + 1} / {tasks.length}</StatusPill><button onClick={pause} className="btn-secondary"><Pause />Pause</button></div>
      </div>
      <div className="mb-5 h-2 rounded-full bg-slate-800"><div className="h-full rounded-full bg-violet-400" style={{ width: `${(index / tasks.length) * 100}%` }} /></div>
      <div className="grid gap-5 xl:grid-cols-2">
        <MeasurementGuide definition={guideDef} />
        <div className="panel p-6">
          {isSpecial ? (
            <div className="space-y-4">
              <p className="text-sm leading-6 text-slate-300">{task.explanation}</p>
              <p className="text-sm text-amber-300">This step is completed on the Component Dimension screen.</p>
              <Link to={`/components/${session.component_uuid}/dimensions`} className="btn-primary w-full">Open component dimensions<ExternalLink /></Link>
              <button disabled={busy} onClick={() => advance()} className="btn-secondary w-full">Mark as done & continue</button>
            </div>
          ) : (
            <MeasurementEntry key={task.uuid || task.key} definition={guideDef} onSave={save} onSkip={skip} busy={busy} />
          )}
        </div>
      </div>
      <div className="mt-5"><BoundaryNotice compact /></div>
    </>
  );
}