import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { RotateCcw, Layers, Gauge, Eye, User, Ruler, Box, ChevronDown, ChevronUp, FolderOpen } from 'lucide-react';
import BabylonViewportV2 from '@/components/viewportV2/BabylonViewportV2';
import ViewportV2Diagnostics from '@/components/viewportV2/ViewportV2Diagnostics';
import StatusPill from '@/components/workshop/StatusPill';
import ContextInspectorV2 from '@/components/workshop3d/ContextInspectorV2';
import { base44 } from '@/api/base44Client';
import { loadProjectGeometry } from '@/services/measurementGeometryService';

const MODES = [
  { id: 'internal', label: 'Internal', icon: Box },
  { id: 'cover', label: 'Cover Preview', icon: Layers },
  { id: 'fit', label: 'Fit Comparison', icon: Eye },
  { id: 'measure', label: 'Measurement', icon: Ruler },
];

function uuid() { return (crypto.randomUUID && crypto.randomUUID()) || 'id-' + Math.random().toString(36).slice(2); }

export default function ViewportV2Test() {
  const [viewCommand, setViewCommand] = useState(null);
  const [compatibility, setCompatibility] = useState(false);
  const [diagnostics, setDiagnostics] = useState(null);
  const [selection, setSelection] = useState(null);
  const [mode, setMode] = useState('cover');
  const [showAllLabels, setShowAllLabels] = useState(false);
  const [humanReference, setHumanReference] = useState(false);

  const [projects, setProjects] = useState([]);
  const [selectedProjectId, setSelectedProjectId] = useState('');
  const [project, setProject] = useState(null);
  const [sessions, setSessions] = useState([]);
  const [sessionId, setSessionId] = useState('');
  const [geometry, setGeometry] = useState(null);
  const [loadingProj, setLoadingProj] = useState(false);
  const [diagOpen, setDiagOpen] = useState(false);

  const onDiagnostics = useCallback((snap) => setDiagnostics(snap), []);
  const onSelectionChanged = useCallback((meta) => setSelection(meta), []);
  const fire = (preset) => setViewCommand({ preset, ts: Date.now() });

  useEffect(() => {
    base44.entities.CoverProject.list()
      .then((list) => setProjects((list || []).filter((p) => p.record_state !== 'archived')))
      .catch(() => setProjects([]));
  }, []);

  const loadProject = useCallback(async (projectId) => {
    setSelectedProjectId(projectId);
    if (!projectId) { setGeometry(null); setProject(null); setSessions([]); setSessionId(''); return; }
    setLoadingProj(true);
    try {
      const geo = await loadProjectGeometry(projectId);
      setGeometry(geo);
      setProject(geo.project);
      let sess = geo.sessions || [];
      if (!sess.length) {
        // auto-create a draft measurement session so station saves work immediately
        const today = new Date().toISOString().slice(0, 10);
        const proj = geo.project;
        const created = await base44.entities.MeasurementSession.create({
          uuid: uuid(),
          project_uuid: projectId,
          customer_uuid: (proj && proj.customer_uuid) || 'unknown',
          workflow: 'below-knee-cover',
          status: 'In progress',
          measured_date: today,
        });
        sess = [created];
      }
      setSessions(sess);
      setSessionId(sess[0] && sess[0].uuid);
    } catch (_) {
      setGeometry(null);
    } finally {
      setLoadingProj(false);
    }
  }, []);

  const reloadGeometry = useCallback(async () => {
    if (!selectedProjectId) return;
    const geo = await loadProjectGeometry(selectedProjectId);
    setGeometry(geo);
    setProject(geo.project);
    setSessions(geo.sessions || []);
  }, [selectedProjectId]);

  const selectionLabel = selection
    ? selection.type === 'measurementStation'
      ? `Station — ${selection.stationName}`
      : selection.label || selection.partId || 'Item'
    : null;

  return (
    <div className="flex h-screen flex-col bg-workshop">
      <header className="flex items-center gap-3 border-b border-shire-border px-4 py-3">
        <div>
          <h1 className="text-lg font-semibold text-white">SHiRE LimbForge Workshop</h1>
          <p className="text-xs text-slate-500">Measurement-driven 3D — independent Babylon.js viewport.</p>
        </div>
        <div className="ml-auto flex items-center gap-2">
          {diagnostics?.coreError
            ? <StatusPill tone="red">Engine error</StatusPill>
            : diagnostics?.renderLoopActive
              ? <StatusPill tone="green">Viewport live</StatusPill>
              : <StatusPill tone="amber">Initialising</StatusPill>}
          <Link to="/dashboard" className="btn-secondary !px-3 !py-2 text-xs">Dashboard</Link>
        </div>
      </header>

      <div className="flex flex-1 flex-col gap-3 overflow-hidden p-3 lg:flex-row">
        <div className="flex min-h-0 flex-1 flex-col">
          <div className="mb-2 flex flex-wrap items-center gap-2">
            <div className="flex items-center gap-1 rounded-xl border border-shire-border bg-shire-raised p-1">
              {MODES.map((m) => {
                const Icon = m.icon;
                const active = mode === m.id;
                return (
                  <button key={m.id} onClick={() => setMode(m.id)} className={`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition ${active ? 'bg-shire-purple text-white' : 'text-slate-400 hover:text-shire-purple-bright'}`}>
                    <Icon className="h-3.5 w-3.5" />{m.label}
                  </button>
                );
              })}
            </div>
            <span className="mx-1 h-5 w-px bg-white/10" />
            {['Front', 'Rear', 'Medial', 'Lateral', 'Top', 'Fit'].map((v) => (
              <button key={v} onClick={() => fire(v.toLowerCase())} className="btn-secondary !py-1.5 text-xs">{v}</button>
            ))}
            <button onClick={() => fire('reset')} className="btn-secondary !py-1.5 text-xs"><RotateCcw className="mr-1 h-3.5 w-3.5" />Reset</button>
            <span className="mx-1 h-5 w-px bg-white/10" />
            <button onClick={() => setShowAllLabels((s) => !s)} className={`btn-secondary !py-1.5 text-xs ${showAllLabels ? '!border-violet-400/50 !text-violet-300' : ''}`}><Eye className="mr-1 h-3.5 w-3.5" />{showAllLabels ? 'Labels: All' : 'Labels: Selected'}</button>
            <button onClick={() => setHumanReference((h) => !h)} className={`btn-secondary !py-1.5 text-xs ${humanReference ? '!border-emerald-400/50 !text-emerald-300' : ''}`}><User className="mr-1 h-3.5 w-3.5" />Human Ref</button>
            <button onClick={() => setCompatibility((c) => !c)} className={`btn-secondary !py-1.5 text-xs ${compatibility ? '!border-amber-400/50 !text-amber-300' : ''}`}><Layers className="mr-1 h-3.5 w-3.5" />Compat</button>
          </div>

          <div className="mb-2 flex flex-wrap items-center gap-2">
            <FolderOpen className="h-4 w-4 text-slate-500" />
            <select value={selectedProjectId} onChange={(e) => loadProject(e.target.value)} className="workshop-input !mt-0 !min-h-9 max-w-xs">
              <option value="">{projects.length ? 'Select a cover project…' : 'No projects — create one in Customers'}</option>
              {projects.map((p) => <option key={p.id} value={p.uuid}>{p.data_label || p.project_id || 'Project'}</option>)}
            </select>
            {sessions.length > 0 && (
              <select value={sessionId} onChange={(e) => setSessionId(e.target.value)} className="workshop-input !mt-0 !min-h-9 max-w-xs">
                {sessions.map((s) => <option key={s.id} value={s.uuid}>{s.workflow} · {s.status}</option>)}
              </select>
            )}
            {loadingProj && <span className="text-xs text-slate-500">Loading geometry…</span>}
            {geometry && <StatusPill tone={geometry.statusTone}>{geometry.geometryStatus}</StatusPill>}
            <div className="ml-auto text-xs">{selectionLabel ? <span className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-slate-300">Selected: <span className="font-semibold text-violet-300">{selectionLabel}</span></span> : <span className="text-slate-500">No selection</span>}</div>
          </div>

          <div className="panel relative min-h-0 flex-1 overflow-hidden">
            <BabylonViewportV2
              viewCommand={viewCommand}
              compatibility={compatibility}
              mode={mode}
              showAllLabels={showAllLabels}
              humanReference={humanReference}
              geometry={geometry}
              onSelectionChanged={onSelectionChanged}
              onDiagnostics={onDiagnostics}
            />
          </div>
        </div>

        <aside className="panel flex w-full shrink-0 flex-col overflow-hidden lg:w-96">
          <div className="min-h-0 flex-1 overflow-hidden">
            <ContextInspectorV2
              selection={selection}
              project={project}
              sessionId={sessionId}
              geometry={geometry}
              onSaved={reloadGeometry}
            />
          </div>
          <div className="shrink-0 border-t border-shire-border">
            <button onClick={() => setDiagOpen((o) => !o)} className="flex w-full items-center justify-between px-4 py-2.5 text-xs font-semibold text-slate-300 hover:text-shire-purple-bright">
              <span className="flex items-center gap-2"><Gauge className="h-4 w-4" />Viewport diagnostics</span>
              {diagOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
            </button>
            {diagOpen && (
              <div className="max-h-60 overflow-y-auto px-4 pb-4">
                <ViewportV2Diagnostics snapshot={diagnostics} />
              </div>
            )}
          </div>
        </aside>
      </div>
    </div>
  );
}