import { useEffect, useState } from 'react';
import { Play, Cpu, AlertCircle } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import StatusBadge from '@/components/app/StatusBadge';
import { useExperienceMode } from '@/lib/ExperienceMode';
import { GeometryService, buildGeometryRequest } from '@/lib/geometryService';
import { storageAdapter } from '@/lib/storageAdapter';

export default function Jobs() {
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [jobs, setJobs] = useState([]);
  const [projects, setProjects] = useState([]);
  const [selected, setSelected] = useState('');
  const [busy, setBusy] = useState(false);
  const [settings, setSettings] = useState(null);

  const load = () => Promise.all([
    base44.entities.GeometryJob.list('-created_date').catch(() => []),
    base44.entities.CoverCanvasProject.list('-updated_date').catch(() => []),
    base44.entities.SystemSettings.list(null, 1).catch(() => [])
  ]).then(([j, p, s]) => {
    const safeJ = Array.isArray(j) ? j : [];
    const safeP = Array.isArray(p) ? p : [];
    const safeS = Array.isArray(s) ? s[0] : null;
    setJobs(safeJ); setProjects(safeP); setSettings(safeS);
    setSelected(prev => prev || (safeP[0] ? safeP[0].id : ''));
  });

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

  const submit = async () => {
    if (!selected) return;
    setBusy(true);
    let request = { simulation: true, project_id: selected };
    try {
      const project = await base44.entities.CoverCanvasProject.get(selected);
      const [layers, assets] = await Promise.all([
        base44.entities.ArtworkLayer.filter({ projectId: selected }).catch(() => []),
        base44.entities.ArtworkAsset.filter({ projectId: selected }).catch(() => [])
      ]);
      let cover = null;
      if (project?.coverModelId) { try { cover = await base44.entities.CoverModel.get(project.coverModelId); } catch { cover = null; } }
      request = buildGeometryRequest({ project, cover, layers: Array.isArray(layers) ? layers : [], assets: Array.isArray(assets) ? assets : [] });
    } catch { /* fall back to minimal request */ }
    try {
      const job = await base44.entities.GeometryJob.create({ projectId: selected, jobType: 'projection_preview', status: 'processing', progress: 20, requestPayload: request });
      await GeometryService.createProjectionPreview(request);
      await base44.entities.GeometryJob.update(job.id, { status: 'completed', progress: 100, completedDate: new Date().toISOString(), resultPayload: { simulation: true, request } });
    } catch { /* simulation best-effort */ }
    setBusy(false);
    load();
  };
  const canFinal = storageAdapter.canFinalize(settings);
  const safeJobs = Array.isArray(jobs) ? jobs : [];
  const safeProjects = Array.isArray(projects) ? projects : [];

  return (
    <>
      <PageHeader eyebrow="Processing" title={guided ? 'Processing' : 'Processing jobs'} description={guided ? 'Run a preview to see how your design looks in 3D. Final processing needs the live geometry engine and SHiRE storage.' : 'Preview simulations run in the browser. Final processing requires the live geometry engine and writable SHiREVault.'} />

      <div className="panel mb-5 flex flex-col gap-3 md:flex-row md:items-center">
        <select value={selected} onChange={e => setSelected(e.target.value)} className="field md:max-w-xs">{safeProjects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}</select>
        <button disabled={!selected || busy} onClick={submit} className="btn-primary min-w-max"><Play size={17} />{busy ? 'Running…' : guided ? 'Run preview' : 'Submit preview simulation'}</button>
        <button disabled={!canFinal} title={canFinal ? '' : 'Requires live service and writable SHiREVault'} className="btn-secondary min-w-max">Submit final processing</button>
      </div>
      <div className="warning-box mb-5">{guided ? 'Final processing is unavailable until the live geometry engine and SHiRE storage are connected.' : 'Final processing is blocked until the deployment adapter verifies a live geometry service and writable SHiREVault at /SHiRELimbs.'}</div>

      <div className="panel">
        <h2 className="section-title"><Cpu size={16} />{guided ? 'Your processing jobs' : 'Job queue'}</h2>
        {safeJobs.map(j => {
          const active = j.status === 'processing';
          const name = safeProjects.find(p => p.id === j.projectId)?.name || j.projectId;
          return (
            <div key={j.id} className={`grid grid-cols-1 gap-3 border-t border-white/[0.06] py-4 md:items-center ${guided ? 'md:grid-cols-[1.4fr_1.2fr_auto]' : 'md:grid-cols-[1.4fr_1fr_1.2fr_auto]'}`}>
              <div>
                <p className="text-sm font-medium text-white">{name}</p>
                <p className="mono text-[10px] text-slate-500">{j.id.slice(0, 12)}</p>
              </div>
              {!guided && (
                <div className="text-xs text-slate-400">
                  <p>Operation: <span className="capitalize text-slate-200">{j.jobType?.replaceAll('_', ' ')}</span></p>
                  <p>Engine: <span className="text-slate-200">{j.simulation ? 'simulation' : 'live'}</span></p>
                </div>
              )}
              <div className="flex items-center gap-3">
                <div className="h-2 flex-1 overflow-hidden rounded-full bg-slate-800">
                  <div className={`h-2 rounded-full ${active ? 'pulse-dot bg-cyan-400' : j.status === 'completed' ? 'bg-cyan-400' : 'bg-slate-600'}`} style={{ width: `${j.progress}%` }} />
                </div>
                <span className="mono text-xs text-slate-300">{j.progress}%</span>
              </div>
              <div className="flex items-center gap-2">
                {j.errorMessage && <AlertCircle size={15} className="text-red-400" title={j.errorMessage} />}
                <span className="mono hidden text-[10px] text-slate-500 lg:block">{j.startedDate || j.created_date ? new Date(j.startedDate || j.created_date).toLocaleTimeString() : '—'}</span>
                <StatusBadge status={j.status} />
              </div>
            </div>
          );
        })}
        {!safeJobs.length && <p className="empty">No processing jobs yet.</p>}
      </div>
    </>
  );
}