import { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { Sparkles, ShieldCheck, Plug, Lock, Eye, ChevronDown } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import Breadcrumbs from '@/components/workshop/Breadcrumbs';
import StatusPill from '@/components/workshop/StatusPill';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import BabylonViewportV2 from '@/components/viewportV2/BabylonViewportV2';
import DesignHierarchy from '@/components/design/DesignHierarchy';
import DesignInspector from '@/components/design/DesignInspector';
import DesignModeBar from '@/components/design/DesignModeBar';
import { adapters } from '@/services/serviceConfig';
import { projectService } from '@/services/projectService';
import { customerService } from '@/services/customerService';
import { designService, defaultConfig } from '@/services/designService';
import { ossiguardService } from '@/services/ossiguardService';
import { loadProjectGeometry } from '@/services/measurementGeometryService';

export default function DesignForge() {
  const { projectId } = useParams();
  const navigate = useNavigate();
  const [projects, setProjects] = useState(null);
  const [activeProjectId, setActiveProjectId] = useState(projectId || null);
  const [data, setData] = useState(null);
  const [busy, setBusy] = useState(false);
  const [geometry, setGeometry] = useState(null);
  const [diagnostics, setDiagnostics] = useState(null);
  const [viewCommand, setViewCommand] = useState(null);
  const [mode, setMode] = useState('cover');
  const [showAllLabels, setShowAllLabels] = useState(false);
  const [showOssiguard, setShowOssiguard] = useState(true);
  const [selected, setSelected] = useState('cover');
  const [form, setForm] = useState(defaultConfig(null));
  const [visibility, setVisibility] = useState({});
  const [locks, setLocks] = useState({ fit: true, zones: true });

  // Project picker for /design-forge with no projectId
  useEffect(() => {
    if (projectId) { setActiveProjectId(projectId); return; }
    projectService.list().then((list) => {
      const active = (list || []).filter((p) => p.record_state !== 'archived' && p.status !== 'Archived');
      setProjects(active);
    });
  }, [projectId]);

  const load = useCallback(async () => {
    if (!activeProjectId) return;
    const project = await projectService.get(activeProjectId);
    if (!project) { setData({ notFound: true }); return; }
    const [customer, limb, design, ossiguard, designRevisions] = await Promise.all([
      project.customer_uuid ? customerService.get(project.customer_uuid) : Promise.resolve(null),
      project.limb_profile_uuid ? adapters.database.filter('LimbProfile', { uuid: project.limb_profile_uuid }, '-updated_date', 1) : Promise.resolve([]),
      designService.getCurrent(activeProjectId),
      project.ossiguard_profile_uuid ? ossiguardService.get(project.ossiguard_profile_uuid) : Promise.resolve(null),
      designService.forProject(activeProjectId),
    ]);
    setGeometry(null);
    try { setGeometry(await loadProjectGeometry(activeProjectId)); } catch (_) {}
    setForm({ ...defaultConfig(project), ...(design || {}) });
    setData({ project, customer, limb: limb[0], design, ossiguard, designRevisions: designRevisions || [] });
  }, [activeProjectId]);

  useEffect(() => { if (activeProjectId) load(); }, [load]);

  const set = (key, value) => setForm((f) => ({ ...f, [key]: value }));
  const fire = (preset) => setViewCommand({ preset, ts: Date.now() });
  const toggleVis = (id, val) => setVisibility((v) => ({ ...v, [id]: val === undefined ? !(v[id] !== false) : val }));
  const toggleLock = (id, val) => setLocks((l) => ({ ...l, [id]: val === undefined ? !l[id] : val }));

  const conflicts = useMemo(() => {
    if (!data?.ossiguard) return null;
    const v = designService.validate(form, data.project, data.ossiguard);
    const c = {};
    (v.issueObjects || []).forEach((i) => {
      if (i.level === 'blocked' || i.level === 'warning') {
        if (i.text.toLowerCase().includes('ossiguard') || i.text.toLowerCase().includes('connector') || i.text.toLowerCase().includes('fastener')) c.ossiguard = i.text;
        if (i.text.toLowerCase().includes('pattern')) c.patterns = i.text;
        if (i.text.toLowerCase().includes('text')) c['custom-text'] = i.text;
        if (i.text.toLowerCase().includes('logo')) c.branding = i.text;
      }
    });
    return c;
  }, [form, data]);

  const logoVal = useMemo(() => designService.logoValidation(form, data?.project, data?.ossiguard), [form, data]);

  const act = (fn) => async (...args) => { setBusy(true); try { await fn(...args); await load(); } finally { setBusy(false); } };
  const save = act(() => designService.saveRevision(activeProjectId, { ...form, project_uuid: activeProjectId, customer_uuid: data.project.customer_uuid }, 'Ray'));
  const duplicate = act(() => designService.duplicate(activeProjectId, 'Ray'));
  const approve = act(async () => { const r = await designService.approveForQuote(data.design.uuid, 'Ray'); if (r && r.error) { alert(r.error + '\n\n' + (r.validation?.issues || []).join('\n')); } });

  if (!activeProjectId) {
    return (
      <>
        <PageHeader eyebrow="Workshop" title="Design Forge" description="Select a cover project to open the design workshop." />
        {!projects ? <LoadingPanel /> : projects.length === 0 ? <div className="panel p-8 text-center text-slate-500">No active cover projects. <Link className="text-violet-300" to="/projects">View projects</Link></div> : (
          <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">{projects.map((p) => (
            <button key={p.uuid} onClick={() => navigate(`/projects/${p.uuid}/design-forge`)} className="panel p-4 text-left hover:border-shire-purple/40">
              <div className="font-medium text-violet-200">{p.project_id}</div><div className="mt-1 text-xs text-slate-400">{p.status}</div>
            </button>))}</div>
        )}
      </>
    );
  }

  if (!data) return <LoadingPanel label="Loading Design Forge" />;
  if (data.notFound) return <div className="panel mx-auto mt-10 max-w-lg p-8 text-center"><h1 className="text-xl font-semibold text-white">Project not found</h1><Link className="btn-secondary mt-4" to="/projects">Back to projects</Link></div>;
  const { project, customer, limb, design, ossiguard } = data;

  return (
    <>
      <Breadcrumbs items={[{ label: 'Cover Projects', to: '/projects' }, { label: project.project_id, to: `/projects/${project.uuid}` }, { label: 'Design Forge' }]} />
      <PageHeader eyebrow={`${project.project_id} · REV ${project.revision}`} title="Design Forge" description="Conceptual cosmetic cover design — not manufacturing CAD. Fit and safety geometry locked." action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to={`/projects/${project.uuid}`}>Back to project</Link>{ossiguard && <Link className="btn-secondary" to={`/ossiguard/${ossiguard.uuid}`}><Plug className="h-4 w-4" />Ossiguard</Link>}</div>} />

      <div className="mb-4 flex flex-wrap items-center gap-2">
        <StatusPill tone="green"><Lock className="mr-1 inline h-3 w-3" />Fit Geometry Locked</StatusPill>
        <StatusPill tone={design?.validation_status === 'Pass' ? 'green' : design?.validation_status === 'Blocked' ? 'red' : 'amber'}>Design: {design ? `v${design.version} · ${design.validation_status || 'Warning'}` : 'Not saved'}</StatusPill>
        {ossiguard ? <StatusPill tone="cyan"><Plug className="mr-1 inline h-3 w-3" />Ossiguard: {ossiguard.profile_name} rev{ossiguard.connector_revision}</StatusPill> : <StatusPill tone="slate">No Ossiguard</StatusPill>}
        {design?.approved_for_quote && <StatusPill tone="green">Approved for Quote</StatusPill>}
        <span className="ml-auto text-xs text-slate-500">{diagnostics?.renderLoopActive ? 'Viewport live' : 'Initialising'}</span>
      </div>

      <div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <SummaryCard label="Customer" value={customer?.full_name || '—'} link={customer ? `/customers/${customer.uuid}` : null} />
        <SummaryCard label="Limb" value={limb?.configuration || '—'} />
        <SummaryCard label="Prosthesis" value={project.prosthesis_configuration || '—'} />
        <SummaryCard label="Geometry" value={geometry?.geometryStatus || 'Generic model'} />
      </div>

      <div className="grid gap-4 lg:grid-cols-[260px_1fr_340px]">
        <div className="hidden lg:block"><DesignHierarchy selected={selected} onSelect={setSelected} visibility={visibility} onToggleVisibility={toggleVis} locks={locks} onToggleLock={toggleLock} conflicts={conflicts} /></div>

        <div className="panel overflow-hidden">
          <DesignModeBar mode={mode} onMode={setMode} showOssiguard={showOssiguard} onToggleOssiguard={() => setShowOssiguard((s) => !s)} hasOssiguard={!!ossiguard} />
          <div className="flex flex-wrap items-center gap-1.5 border-b border-shire-border p-2">
            {['Front','Rear','Medial','Lateral','Top','Reset'].map((v) => <button key={v} onClick={() => fire(v.toLowerCase())} className="btn-secondary !py-1 !px-2.5 text-xs">{v}</button>)}
            <button onClick={() => setShowAllLabels((s) => !s)} className={`btn-secondary !py-1 text-xs ${showAllLabels ? '!border-violet-400/50 !text-violet-300' : ''}`}><Eye className="h-3.5 w-3.5" />{showAllLabels ? 'All' : 'Sel'}</button>
          </div>
          <div className="h-[420px] lg:h-[560px] w-full bg-shire-viewport">
            <BabylonViewportV2 viewCommand={viewCommand} mode={mode === 'internal' ? 'internal' : mode === 'fit' || mode === 'fit-comparison' ? 'fit' : 'cover'} showAllLabels={showAllLabels} geometry={geometry} designConfig={form} ossiguardProfile={ossiguard} showOssiguard={showOssiguard && !!ossiguard} onDiagnostics={setDiagnostics} />
          </div>
          <div className="flex items-center gap-2 border-t border-shire-border p-2 lg:hidden">
            <select className="workshop-input !py-1.5" value={selected} onChange={(e) => setSelected(e.target.value)}>
              {['cover','fit','cover-shell','panels','vent','ossiguard','zones','branding','custom-text','patterns','accents','colour'].map((id) => <option key={id} value={id}>{id}</option>)}
            </select>
          </div>
        </div>

        <DesignInspector element={selected} form={form} set={set} project={project} design={design} ossiguard={ossiguard} busy={busy} onSave={save} onDuplicate={duplicate} onApprove={approve} conflicts={conflicts} logoValidation={logoVal} />
      </div>
    </>
  );
}

function SummaryCard({ label, value, link }) {
  const content = <><div className="text-xs uppercase tracking-wide text-slate-500">{label}</div><div className="mt-1 truncate text-sm text-slate-200">{value}</div></>;
  return <div className="panel p-3">{link ? <Link to={link} className="hover:text-violet-300">{content}</Link> : content}</div>;
}