import React, { useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { CirclePause, CirclePlay, Flag, KeyRound, Octagon, RotateCcw, Square } from 'lucide-react';
import CoverageOrb from '@/components/scanforge/CoverageOrb';
import { useScanner } from '@/context/ScannerContext';

const views = ['RGB view', 'Depth view', 'RGB + depth', 'Depth-colour overlay', 'Live point cloud', 'Silhouette mask', 'Captured coverage'];

export default function LiveCapture() {
  const location = useLocation();
  const projectId = useMemo(() => new URLSearchParams(location.search).get('projectId'), [location.search]);
  const { status, demo, scanState, setScanState, performAction } = useScanner();
  const [view, setView] = useState('Depth view');
  const [running, setRunning] = useState(false);
  const [paused, setPaused] = useState(false);
  const [coverage, setCoverage] = useState(0);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!demo || !running || paused) return undefined;
    const timer = window.setInterval(() => setCoverage((value) => Math.min(100, value + 1)), 700);
    return () => window.clearInterval(timer);
  }, [demo, paused, running]);

  useEffect(() => {
    if (typeof scanState.progress === 'number' && !demo) setCoverage(scanState.progress);
    setRunning(scanState.operation === 'capturing' || scanState.operation === 'paused');
    setPaused(scanState.operation === 'paused');
  }, [demo, scanState.operation, scanState.progress]);

  const run = async (action, optimisticOperation) => {
    if (!projectId && !demo) { setError('No ScanForge project ID was supplied. Return to New Scan and create a project first.'); return; }
    setBusy(true);
    setError('');
    try {
      if (demo) {
        setScanState((current) => ({ ...current, operation: optimisticOperation, activeProjectId: 'demo-project', activeProjectName: 'Demo Scan' }));
      } else {
        await performAction(action, { projectId }, true);
        setScanState((current) => ({ ...current, operation: optimisticOperation, activeProjectId: projectId }));
      }
      setRunning(['capturing', 'paused'].includes(optimisticOperation));
      setPaused(optimisticOperation === 'paused');
    } catch (reason) {
      setError(reason?.message || 'Scanner action failed');
    } finally {
      setBusy(false);
    }
  };

  const ready = demo || status === 'ready' || scanState.operation === 'paused';

  return (
    <div className="mx-auto max-w-[1500px] space-y-3">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div><p className="text-xs uppercase tracking-[.28em] text-purple-300">Capture workspace</p><h2 className="mt-1 text-2xl font-semibold">Live Capture</h2><p className="mt-1 text-xs text-zinc-600">Project: {projectId || (demo ? 'demo-project' : 'not selected')}</p></div>
        <select value={view} onChange={(event) => setView(event.target.value)} className="rounded-xl border border-white/10 bg-[#111114] px-4 py-2 text-sm">{views.map((item) => <option key={item}>{item}</option>)}</select>
      </div>
      {demo && <div className="rounded-xl border border-purple-400/40 bg-purple-500/10 py-2 text-center text-sm font-bold tracking-[.25em] text-purple-200">DEMO SCANNER MODE</div>}
      {status === 'offline' && !demo && <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-center text-sm font-bold text-red-300">SCANFORGE AGENT OFFLINE — capture controls are locked</div>}
      {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200">{error}</div>}
      <div className="grid gap-3 xl:grid-cols-[1fr_280px]">
        <div className="scan-lines relative flex min-h-[52vh] items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_center,#25202c,#0a0a0c_65%)]">
          <div className="text-center"><p className="text-xs uppercase tracking-[.3em] text-zinc-500">{view}</p><p className="mt-3 text-sm text-zinc-600">{demo ? 'Simulated preview feed' : running ? 'Waiting for authenticated agent preview stream' : 'Capture is idle'}</p></div>
          {demo && <div className="absolute inset-0 flex rotate-[-18deg] items-center justify-center text-6xl font-black text-purple-400/[.07]">DEMO</div>}
        </div>
        <div className="space-y-3 rounded-2xl border border-white/10 bg-[#111114] p-4">
          <CoverageOrb value={coverage}/>
          <div className="grid grid-cols-2 gap-2 text-xs">
            {[
              ['Elapsed', running ? 'Active' : '00:00:00'], ['Frames', demo ? coverage * 12 : scanState.frames || 0],
              ['Accepted', demo ? coverage * 10 : scanState.acceptedFrames || 0], ['Rejected', demo ? coverage * 2 : scanState.rejectedFrames || 0],
              ['Tracking', demo && running ? '92%' : scanState.trackingConfidence || '—'], ['Distance', demo && running ? '1.1 m' : scanState.distance || '—'],
              ['Points', demo ? `${coverage * 18}k` : scanState.pointCount || 0], ['Dropped', demo ? 2 : scanState.droppedFrames || 0]
            ].map(([name, value]) => <div key={name} className="rounded-lg bg-black/30 p-2"><p className="text-zinc-600">{name}</p><p className="mt-1 text-zinc-200">{value}</p></div>)}
          </div>
          <p className="rounded-xl border border-[#7dff72]/20 bg-[#7dff72]/5 p-3 text-center text-sm text-[#b4ffad]">{scanState.guidance || (running ? (paused ? 'Scan paused' : 'Move slowly around the object') : 'Hold steady and prepare the capture area')}</p>
        </div>
      </div>
      <div className="sticky bottom-16 z-20 flex flex-wrap items-center justify-center gap-2 rounded-2xl border border-white/10 bg-[#111114]/95 p-3 backdrop-blur lg:bottom-3">
        <button onClick={() => run('start_capture', 'capturing')} disabled={busy || running || !ready} className="flex items-center gap-2 rounded-xl bg-[#7dff72] px-4 py-3 text-sm font-bold text-black disabled:opacity-25"><CirclePlay size={18}/>Start</button>
        <button onClick={() => run('pause_capture', 'paused')} disabled={busy || !running || paused} className="control"><CirclePause/>Pause</button>
        <button onClick={() => run('resume_capture', 'capturing')} disabled={busy || !running || !paused} className="control"><CirclePlay/>Resume</button>
        <button onClick={() => performAction('start_capture', { projectId, keyframeOnly: true }, false).catch((reason) => setError(reason.message))} disabled={busy || !running || paused || demo} className="control"><KeyRound/>Keyframe</button>
        <button onClick={() => performAction('start_capture', { projectId, undoLastSegment: true }, true).catch((reason) => setError(reason.message))} disabled={busy || !running || demo} className="control"><RotateCcw/>Undo segment</button>
        <button onClick={() => run('finish_capture', 'processing')} disabled={busy || !running} className="control"><Flag/>Finish</button>
        <button onClick={() => run('cancel_capture', 'idle')} disabled={busy || !running} className="control"><Square/>Cancel</button>
        <button onClick={() => run('cancel_capture', 'idle')} disabled={busy || !running} className="flex items-center gap-2 rounded-xl bg-red-600 px-4 py-3 text-sm font-bold disabled:opacity-25"><Octagon/>Emergency Stop</button>
      </div>
    </div>
  );
}
