import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Box, ArrowRight, Cpu } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import StatusBadge from '@/components/app/StatusBadge';
import ProjectCard from '@/components/app/ProjectCard';
import SegmentProgress from '@/components/app/SegmentProgress';
import { useExperienceMode } from '@/lib/ExperienceMode';

export default function ProjectHistory() {
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [projects, setProjects] = useState([]);
  const [covers, setCovers] = useState([]);
  const [jobs, setJobs] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      base44.entities.CoverCanvasProject.list('-updated_date', 50).catch(() => []),
      base44.entities.CoverModel.list().catch(() => []),
      base44.entities.GeometryJob.list('-updated_date', 50).catch(() => [])
    ]).then(([p, c, j]) => {
      setProjects(Array.isArray(p) ? p : []);
      setCovers(Array.isArray(c) ? c : []);
      setJobs(Array.isArray(j) ? j : []);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const safeCovers = Array.isArray(covers) ? covers : [];
  const safeJobs = Array.isArray(jobs) ? jobs : [];
  const coverMap = Object.fromEntries(safeCovers.map(c => [c.id, c]));
  const jobsByProject = safeJobs.reduce((m, j) => { (m[j.projectId] = m[j.projectId] || []).push(j); return m; }, {});

  return (
    <>
      <PageHeader eyebrow="Archive" title="Project history" description="Every CoverCanvas project, its input method, status and the geometry jobs it has triggered." />
      {loading && <div className="panel empty">Loading projects…</div>}
      {!loading && !projects.length && (
        <div className="panel empty">
          <Box className="mx-auto mb-3 text-slate-600" />
          No projects yet. Start one from the New Project wizard.
          <div className="mt-4"><Link to="/new-project" className="btn-primary">Start a project<ArrowRight size={17} /></Link></div>
        </div>
      )}
      {guided ? (
        <section className="space-y-3">
          {projects.map(p => <ProjectCard key={p.id} project={p} cover={coverMap[p.coverModelId]} jobsCount={(jobsByProject[p.id] || []).length} />)}
        </section>
      ) : (
        <div className="grid gap-5 xl:grid-cols-[1.6fr_1fr]">
          <section className="space-y-3">
            {projects.map(p => <ProjectCard key={p.id} project={p} cover={coverMap[p.coverModelId]} jobsCount={(jobsByProject[p.id] || []).length} />)}
          </section>
          <aside className="panel h-fit">
            <h2 className="section-title"><Cpu size={16} />Geometry job queue</h2>
            {safeJobs.length ? safeJobs.map(j => (
              <div key={j.id} className="mb-3 flex items-center gap-3 rounded-xl border border-white/[0.06] bg-black/20 p-3 last:mb-0">
                <SegmentProgress value={j.progress || 0} size={48} tone={j.simulation ? 'cyan' : 'violet'} />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium text-white">{j.jobType?.replaceAll('_', ' ')}</p>
                  <p className="mono text-[10px] text-slate-500">{j.id.slice(0, 10)} · {j.simulation ? 'simulation' : 'live'}</p>
                </div>
                <StatusBadge status={j.status} />
              </div>
            )) : <p className="empty">No jobs queued.</p>}
          </aside>
        </div>
      )}
    </>
  );
}