import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Activity, Sparkles, ArrowRight, ShieldAlert, Cpu, Sliders, Plus, RefreshCw, Box, Layers } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import StatusBadge from '@/components/app/StatusBadge';
import SegmentProgress from '@/components/app/SegmentProgress';
import ProjectCard from '@/components/app/ProjectCard';
import { Image as ContentImage } from '@/components/ui/image';
import { useExperienceMode } from '@/lib/ExperienceMode';
import UniversalDesignCard from '@/components/universal/UniversalDesignCard';
import CoverVariantCard from '@/components/universal/CoverVariantCard';

function FriendlyStatus({ tone, label, value }) {
  const dotMap = { ok: 'bg-emerald-400', sim: 'bg-violet-400', warn: 'bg-amber-400', bad: 'bg-red-500', idle: 'bg-slate-600' };
  return (
    <div className="readout">
      <span className="flex items-center gap-2"><span className={`h-2 w-2 rounded-full ${dotMap[tone] || dotMap.idle}`} /><span className="readout-label">{label}</span></span>
      <span className="readout-value">{value}</span>
    </div>
  );
}

export default function Dashboard() {
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [d, setData] = useState({ designs: [], variants: [], covers: [], projects: [], jobs: [], settings: null, concepts: [], layers: [] });

  useEffect(() => {
    Promise.all([
      base44.entities.UniversalDesign.list('-updated_date', 12).catch(() => []),
      base44.entities.CoverDesignVariant.list('-updated_date', 12).catch(() => []),
      base44.entities.CoverModel.filter({ active: true }).catch(() => []),
      base44.entities.CoverCanvasProject.list('-updated_date', 8).catch(() => []),
      base44.entities.GeometryJob.list('-created_date', 6).catch(() => []),
      base44.entities.SystemSettings.list(null, 1).catch(() => []),
      base44.entities.PromptConcept.list('-created_date', 4).catch(() => []),
      base44.entities.UniversalDesignLayer.list('-updated_date', 400).catch(() => [])
    ]).then(([designs, variants, covers, projects, jobs, settings, concepts, layers]) => setData({
      designs: Array.isArray(designs) ? designs : [],
      variants: Array.isArray(variants) ? variants : [],
      covers: Array.isArray(covers) ? covers : [],
      projects: Array.isArray(projects) ? projects : [],
      jobs: Array.isArray(jobs) ? jobs : [],
      settings: Array.isArray(settings) ? (settings[0] || null) : null,
      concepts: Array.isArray(concepts) ? concepts : [],
      layers: Array.isArray(layers) ? layers : []
    })).catch(() => setData({ designs: [], variants: [], covers: [], projects: [], jobs: [], settings: null, concepts: [], layers: [] }));
  }, []);

  const safeDesigns = (d.designs || []).filter(x => !x.archived);
  const safeVariants = d.variants || [];
  const safeCovers = d.covers || [];
  const safeProjects = d.projects || [];
  const safeJobs = d.jobs || [];
  const safeConcepts = d.concepts || [];
  const coverMap = Object.fromEntries(safeCovers.map(c => [c.id, c]));
  const designMap = Object.fromEntries((d.designs || []).map(x => [x.id, x]));
  const variantCountFor = (id) => safeVariants.filter(v => v.universalDesignId === id).length;
  const pieceCountFor = (id) => (d.layers || []).filter(l => l.universalDesignId === id).length;
  const activeJobs = safeJobs.filter(j => j.status === 'processing' || j.status === 'queued');
  const jobCountByProject = safeJobs.reduce((m, j) => { m[j.projectId] = (m[j.projectId] || 0) + 1; return m; }, {});
  const alerts = safeProjects.filter(p => p.validationStatus === 'warning' || p.validationStatus === 'fail');

  const geoStatus = d.settings?.geometryServiceStatus;
  const engineTone = geoStatus === 'connected' ? 'ok' : geoStatus === 'simulation_only' ? 'sim' : 'idle';
  const engineLabel = geoStatus === 'connected' ? 'Ready' : geoStatus === 'simulation_only' ? 'Preview only' : 'Offline';
  const vaultOk = d.settings?.shireVaultStatus === 'connected' && d.settings?.shireVaultWritable;
  const storageLabel = vaultOk ? 'Connected' : 'Not connected';
  const storageTone = vaultOk ? 'ok' : 'warn';
  const recentVariant = safeVariants[0];

  return (
    <>
      <PageHeader
        eyebrow="Design-first"
        title="Your designs"
        description="Create your design once. Fit it to any compatible LimbForge cover. The reusable design stays separate from cover-specific geometry."
        action={<Link to="/settings" className="chip"><Sliders size={13} /> Guided / Advanced</Link>}
      />

      {/* Primary actions */}
      <div className="mb-6 grid gap-3 sm:grid-cols-2">
        <Link to="/create-design" className="group overflow-hidden rounded-2xl border border-cyan-400/25 p-[1px] transition hover:border-cyan-400/50">
          <div className="relative flex h-full items-center justify-between gap-4 rounded-2xl bg-[linear-gradient(120deg,#0c1620,#0a0f16)] p-6">
            <div className="absolute inset-0 opacity-[0.06]" style={{ backgroundImage: 'linear-gradient(rgba(34,211,238,0.4) 1px,transparent 1px),linear-gradient(90deg,rgba(34,211,238,0.4) 1px,transparent 1px)', backgroundSize: '34px 34px', maskImage: 'radial-gradient(ellipse 60% 120% at 0% 50%,#000,transparent 70%)' }} />
            <div className="relative">
              <span className="eyebrow">Start here</span>
              <h2 className="font-heading text-xl font-semibold text-white sm:text-2xl">Create a Universal Design</h2>
              <p className="mt-1 max-w-md text-sm text-slate-400">Start with an idea, image or drawing. We'll adapt it to the cover you choose later.</p>
            </div>
            <span className="relative inline-flex h-12 w-12 items-center justify-center rounded-full border border-cyan-400/40 bg-cyan-400/10 text-cyan-300 transition group-hover:scale-105"><Plus size={22} /></span>
          </div>
        </Link>
        <Link to="/designs" className="group overflow-hidden rounded-2xl border border-violet-400/25 p-[1px] transition hover:border-violet-400/50">
          <div className="relative flex h-full items-center justify-between gap-4 rounded-2xl bg-[linear-gradient(120deg,#15101e,#0a0f16)] p-6">
            <div className="relative">
              <span className="eyebrow text-violet-300">Or reuse</span>
              <h2 className="font-heading text-xl font-semibold text-white sm:text-2xl">Fit a saved design to a cover</h2>
              <p className="mt-1 max-w-md text-sm text-slate-400">Pick a universal design and fit it to any validated cover — the master stays untouched.</p>
            </div>
            <span className="relative inline-flex h-12 w-12 items-center justify-center rounded-full border border-violet-400/40 bg-violet-400/10 text-violet-300 transition group-hover:scale-105"><RefreshCw size={22} /></span>
          </div>
        </Link>
      </div>

      {recentVariant && guided && (
        <Link to={recentVariant.projectId ? `/studio?project=${recentVariant.projectId}` : `/fit-design?design=${recentVariant.universalDesignId}&cover=${recentVariant.coverModelId}`} className="group mb-6 block">
          <div className="panel flex items-center gap-4 transition hover:border-cyan-400/30">
            <div className="grid h-16 w-16 place-items-center overflow-hidden rounded-xl viewport-grid">
              {coverMap[recentVariant.coverModelId]?.previewImageUrl
                ? <ContentImage src={coverMap[recentVariant.coverModelId].previewImageUrl} alt={recentVariant.name} fittingType="fill" className="h-full w-full" />
                : <Box size={22} className="text-cyan-400/40" />}
            </div>
            <div className="flex-1">
              <p className="text-[10px] uppercase tracking-wider text-slate-500">Continue recent cover variant</p>
              <h3 className="font-heading text-sm font-semibold text-white">{recentVariant.name}</h3>
              <div className="mt-1 flex items-center gap-2"><StatusBadge status={recentVariant.status} /><span className="text-[11px] text-slate-500">{recentVariant.summary}</span></div>
            </div>
            <ArrowRight size={18} className="text-slate-500 transition group-hover:text-cyan-300" />
          </div>
        </Link>
      )}

      <div className="mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <FriendlyStatus tone={engineTone} label="Geometry engine" value={engineLabel} />
        <FriendlyStatus tone={storageTone} label="SHiREVault" value={storageLabel} />
        <FriendlyStatus tone="idle" label="Universal designs" value={safeDesigns.length} />
        <FriendlyStatus tone={safeVariants.length ? 'sim' : 'idle'} label="Cover variants" value={safeVariants.length} />
      </div>
      {engineLabel === 'Offline' && (
        <div className="warning-box mb-6">3D processing is temporarily unavailable. You can keep designing and submit for processing later.</div>
      )}

      {/* My Universal Designs */}
      <section className="mb-6">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="section-title mb-0"><Layers size={16} className="text-cyan-300" />My Universal Designs</h2>
          <Link to="/designs" className="chip">View all <ArrowRight size={12} /></Link>
        </div>
        {safeDesigns.length === 0 ? (
          <div className="panel empty">No universal designs yet. <Link to="/create-design" className="text-cyan-300 underline">Create one</Link>.</div>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {safeDesigns.slice(0, 6).map(design => (
              <UniversalDesignCard key={design.id} design={design} variantCount={variantCountFor(design.id)} pieceCount={pieceCountFor(design.id)} />
            ))}
          </div>
        )}
      </section>

      {/* My Cover Variants */}
      <section className="mb-6">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="section-title mb-0"><Box size={16} className="text-violet-300" />My Cover Variants</h2>
          <Link to="/cover-variants" className="chip">View all <ArrowRight size={12} /></Link>
        </div>
        {safeVariants.length === 0 ? (
          <div className="panel empty">No cover variants yet. Fit a universal design to a cover to create one.</div>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {safeVariants.slice(0, 6).map(v => (
              <CoverVariantCard key={v.id} variant={v} design={designMap[v.universalDesignId]} cover={coverMap[v.coverModelId]} />
            ))}
          </div>
        )}
      </section>

      {!guided && (
        <section className="grid gap-6 xl:grid-cols-[1.7fr_1fr]">
          <div>
            <h2 className="section-title">Recent cover-canvas projects</h2>
            <div className="space-y-3">
              {safeProjects.map(p => <ProjectCard key={p.id} project={p} cover={coverMap[p.coverModelId]} jobsCount={jobCountByProject[p.id] || 0} />)}
              {safeProjects.length === 0 && <div className="panel empty">No legacy projects.</div>}
            </div>
            {alerts.length > 0 && (
              <div className="panel mt-4">
                <h2 className="section-title"><ShieldAlert size={16} className="text-amber-300" />Designs needing attention</h2>
                {alerts.map(p => (
                  <div key={p.id} className="mb-2 flex items-center justify-between rounded-lg border border-amber-400/20 bg-amber-400/[0.06] p-3 text-sm last:mb-0">
                    <span className="truncate text-slate-200">{p.name}</span>
                    <Link to={`/validation?project=${p.id}`} className="chip">Fix<ArrowRight size={12} /></Link>
                  </div>
                ))}
              </div>
            )}
          </div>
          <section className="space-y-6">
            <div className="panel">
              <h2 className="section-title"><Cpu size={16} />Designs being processed</h2>
              {activeJobs.length ? activeJobs.map(j => (
                <div key={j.id} className="mb-3 flex items-center gap-4 rounded-xl border border-white/[0.06] bg-black/20 p-3 last:mb-0">
                  <SegmentProgress value={j.progress || 0} size={54} tone="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, 8)}</p></div>
                  <StatusBadge status={j.status} />
                </div>
              )) : <p className="empty">Nothing processing right now.</p>}
            </div>
            <div className="panel">
              <h2 className="section-title"><Sparkles size={16} className="text-violet-300" />Recent concepts</h2>
              <div className="grid grid-cols-2 gap-3">
                {safeConcepts.map(c => (
                  <div key={c.id} className="overflow-hidden rounded-xl border border-white/[0.06]">
                    <div className="grid h-24 place-items-center bg-[radial-gradient(circle_at_50%_40%,#1a1530,#0a0e13_70%)]">{c.previewImageUrl ? <ContentImage src={c.previewImageUrl} alt={c.title} fittingType="fill" className="h-full w-full" /> : <Sparkles size={22} className="text-violet-400/40" />}</div>
                    <p className="truncate p-2 text-xs text-slate-300">{c.title}</p>
                  </div>
                ))}
                {!safeConcepts.length && <div className="empty col-span-2">No concepts yet.</div>}
              </div>
            </div>
          </section>
        </section>
      )}

      <p className="mt-6 text-center text-[11px] text-slate-600">
        <Activity size={11} className="mr-1 inline" />
        Universal designs and adaptation previews are creative only. The final printable shape is created by the LimbForge Geometry Engine during processing.
      </p>
    </>
  );
}