import { useEffect, useState, useMemo } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { Loader2, Box, RefreshCw, GitCompare } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import CoverVariantCard from '@/components/universal/CoverVariantCard';

export default function CoverVariants() {
  const [params] = useSearchParams();
  const filterDesign = params.get('design');
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [variants, setVariants] = useState(null);
  const [designs, setDesigns] = useState([]);
  const [covers, setCovers] = useState([]);

  const load = () => {
    Promise.all([
      base44.entities.CoverDesignVariant.list('-updated_date', 200).catch(() => []),
      base44.entities.UniversalDesign.list('-updated_date', 200).catch(() => []),
      base44.entities.CoverModel.list('-updated_date', 200).catch(() => [])
    ]).then(([v, d, c]) => {
      setVariants(Array.isArray(v) ? v : []);
      setDesigns(Array.isArray(d) ? d : []);
      setCovers(Array.isArray(c) ? c : []);
    }).catch(() => { setVariants([]); setDesigns([]); setCovers([]); });
  };
  useEffect(load, []);

  const designMap = useMemo(() => Object.fromEntries(designs.map(d => [d.id, d])), [designs]);
  const coverMap = useMemo(() => Object.fromEntries(covers.map(c => [c.id, c])), [covers]);
  const visible = useMemo(() => (variants || []).filter(v => !filterDesign || v.universalDesignId === filterDesign), [variants, filterDesign]);

  const switchCover = (v) => { /* opens fit-design for the same design */ window.location.href = `/fit-design?design=${v.universalDesignId}`; };
  const reset = async (v) => {
    await base44.entities.CoverDesignVariant.update(v.id, { adaptationStatus: 'pending', status: 'adapted_preview', adaptationStrategy: 'best_fit' });
    load();
  };

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Cover Variants' : 'Library · Cover Variants'}
        title="My Cover Variants"
        description="Design + target cover combinations. Each variant is a fitted version of a universal design — the master design is never overwritten."
        action={(
          <div className="flex gap-2">
            {filterDesign && <Link to={`/compare?design=${filterDesign}`} className="btn-primary"><GitCompare size={15} /> Compare fits</Link>}
            <Link to="/designs" className="btn-secondary"><Box size={15} /> Universal designs</Link>
          </div>
        )}
      />

      {!variants ? (
        <div className="panel empty"><Loader2 className="mx-auto mb-2 animate-spin text-cyan-300" />Loading variants…</div>
      ) : visible.length === 0 ? (
        <div className="panel fade-in text-center">
          <div className="mx-auto grid h-16 w-16 place-items-center rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-cyan-200"><RefreshCw size={26} /></div>
          <h2 className="mt-4 font-heading text-xl font-semibold text-white">No cover variants yet</h2>
          <p className="mx-auto mt-2 max-w-md text-sm text-slate-400">Fit a universal design to a cover to create your first variant.</p>
          <Link to="/designs" className="btn-primary mx-auto mt-5 inline-flex">Browse universal designs</Link>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {visible.map(v => (
            <CoverVariantCard key={v.id} variant={v} design={designMap[v.universalDesignId]} cover={coverMap[v.coverModelId]} onSwitchCover={switchCover} onReset={reset} />
          ))}
        </div>
      )}

      <p className="mt-6 text-center text-[11px] text-slate-600">Adaptation previews are browser-only. Printable geometry is produced by the LimbForge Geometry Engine during processing.</p>
    </>
  );
}