import { useEffect, useState, useMemo } from 'react';
import { useSearchParams, Link } from 'react-router-dom';
import { Loader2, GitCompare, ArrowLeft, Check } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import AdaptationPreview from '@/components/universal/AdaptationPreview';
import { computeAdaptation } from '@/lib/adaptation';

// Rank variants: best_fit first, then minimal distortion, then by fewer warnings.
const rank = (v) => {
  if (v.adaptationStrategy === 'best_fit') return 0;
  if (v.adaptationStrategy === 'minimal_distortion') return 1;
  if (v.adaptationStrategy === 'front_feature') return 2;
  return 3;
};

export default function CompareVariants() {
  const [params] = useSearchParams();
  const designId = params.get('design');
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';

  const [design, setDesign] = useState(null);
  const [variants, setVariants] = useState([]);
  const [layers, setLayers] = useState([]);
  const [assets, setAssets] = useState([]);
  const [covers, setCovers] = useState([]);
  const [selected, setSelected] = useState([]); // variant ids
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      base44.entities.UniversalDesign.get(designId).catch(() => null),
      base44.entities.CoverDesignVariant.filter({ universalDesignId: designId }).catch(() => []),
      base44.entities.UniversalDesignLayer.filter({ universalDesignId: designId }).catch(() => []),
      base44.entities.ArtworkAsset.filter({ projectId: designId }).catch(() => []),
      base44.entities.CoverModel.list('-updated_date', 200).catch(() => [])
    ]).then(([d, v, l, a, c]) => {
      setDesign(d);
      setVariants(Array.isArray(v) ? v : []);
      setLayers(Array.isArray(l) ? l : []);
      setAssets(Array.isArray(a) ? a : []);
      setCovers(Array.isArray(c) ? c : []);
      // Pre-select up to 3 (or all if fewer).
      setSelected((Array.isArray(v) ? v : []).slice(0, 3).map(x => x.id));
      setLoading(false);
    });
  }, [designId]);

  const coverMap = useMemo(() => Object.fromEntries(covers.map(c => [c.id, c])), [covers]);
  const assetMap = useMemo(() => Object.fromEntries(assets.map(a => [a.id, a])), [assets]);
  const layerImages = useMemo(() => {
    const m = {};
    layers.forEach(l => { const a = assetMap[l.artworkAssetId]; if (a?.originalFile) m[l.id] = a.originalFile; });
    return m;
  }, [layers, assetMap]);

  const sortedVariants = useMemo(() => [...variants].sort((a, b) => rank(a) - rank(b)), [variants]);
  const chosen = useMemo(() => sortedVariants.filter(v => selected.includes(v.id)).slice(0, 4), [sortedVariants, selected]);
  const recommended = chosen[0]?.id || null;

  const toggle = (id) => setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id].slice(0, 4));

  if (loading) return <div className="panel empty"><Loader2 className="mx-auto mb-2 animate-spin text-cyan-300" />Loading variants…</div>;

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Compare cover fits' : 'Comparison · Cover Variants'}
        title="Compare cover fits"
        description="Compare up to four fitted versions of the same universal design across different covers or strategies. The master design is not changed."
        action={<Link to={`/designs`} className="btn-ghost"><ArrowLeft size={15} /> Back to designs</Link>}
      />

      {!design ? (
        <div className="warning-box">Universal design not found.</div>
      ) : variants.length === 0 ? (
        <div className="panel empty">No fitted variants for this design yet. <Link to={`/fit-design?design=${designId}`} className="text-cyan-300 underline">Fit it to a cover</Link>.</div>
      ) : (
        <>
          <p className="mb-3 text-xs text-slate-400">Select up to 4 variants to compare. Recommended fit is highlighted.</p>
          <div className="mb-4 flex flex-wrap gap-2">
            {sortedVariants.map(v => {
              const c = coverMap[v.coverModelId];
              const on = selected.includes(v.id);
              return (
                <button key={v.id} onClick={() => toggle(v.id)} className={`chip ${on ? 'chip-active' : ''}`}>
                  {on && <Check size={12} />} {c?.name || 'Cover'} · {v.adaptationStrategy?.replaceAll('_', ' ')}
                </button>
              );
            })}
          </div>

          {chosen.length === 0 ? (
            <div className="panel empty"><GitCompare size={24} className="mx-auto mb-2 text-cyan-400/40" />Select at least one variant to compare.</div>
          ) : (
            <div className={`grid gap-4 ${chosen.length >= 3 ? 'lg:grid-cols-3 xl:grid-cols-4' : 'sm:grid-cols-2'}`}>
              {chosen.map(v => {
                const cover = coverMap[v.coverModelId] || null;
                const adaptation = (cover && layers.length) ? computeAdaptation({ design, layers, cover, strategy: v.adaptationStrategy || 'best_fit', mirror: v.mirrorMode || 'none' }) : null;
                const clips = (v.clippedRegions?.length) ?? adaptation?.clippedRegions.length ?? 0;
                const reps = (v.repeatedRegions?.length) ?? adaptation?.repeatedRegions.length ?? 0;
                const warnings = (v.protectedZoneWarnings?.length) ?? adaptation?.protectedZoneWarnings.length ?? 0;
                return (
                  <article key={v.id} className={`panel fade-in flex flex-col p-3 ${recommended === v.id ? 'border-cyan-400/50' : ''}`}>
                    <div className="mb-2 flex items-center justify-between">
                      <span className="truncate text-xs font-semibold text-white">{cover?.name || 'Cover'}</span>
                      {recommended === v.id && <span className="rounded-full border border-cyan-400/50 bg-cyan-400/15 px-2 py-0.5 text-[10px] font-semibold text-cyan-100">Best match</span>}
                    </div>
                    {adaptation ? (
                      <AdaptationPreview cover={cover} adaptation={adaptation} layerImages={layerImages} />
                    ) : (
                      <div className="aspect-[3/4] rounded-2xl border border-white/10 grid place-items-center text-xs text-slate-500">No cover preview</div>
                    )}
                    <div className="mt-3 space-y-1.5 text-[11px]">
                      <div className="readout"><span className="readout-label">Strategy</span><span className="readout-value">{(v.adaptationStrategy || 'best_fit').replaceAll('_', ' ')}</span></div>
                      <div className="readout"><span className="readout-label">Cover</span><span className="readout-value">{cover ? `${cover.limbType || '—'} · ${cover.side || '—'}` : 'missing'}</span></div>
                      <div className="readout"><span className="readout-label">Master version</span><span className="readout-value">v{v.universalDesignVersion ?? 1}</span></div>
                      <div className="readout"><span className="readout-label">Clipped pieces</span><span className="readout-value">{clips}</span></div>
                      <div className="readout"><span className="readout-label">Repeated pieces</span><span className="readout-value">{reps}</span></div>
                      <div className="readout"><span className="readout-label">Warnings</span><span className="readout-value">{warnings}</span></div>
                      <div className="readout"><span className="readout-label">Branding</span><span className="readout-value">{v.brandingStatus || 'unverified'}</span></div>
                    </div>
                    {v.summary && <p className="mt-2 rounded-lg border border-cyan-400/20 bg-cyan-400/[0.06] p-2 text-[11px] leading-4 text-cyan-100">{v.summary}</p>}
                    <Link to={`/fit-design?design=${designId}&cover=${v.coverModelId}`} className="btn-secondary mt-3 text-xs">Open this fit</Link>
                  </article>
                );
              })}
            </div>
          )}

          <p className="mt-6 text-center text-[11px] text-slate-600">Comparison uses browser adaptation previews only. Final geometric fit and print readiness are confirmed by the LimbForge Geometry Engine.</p>
        </>
      )}
    </>
  );
}