import { useMemo } from 'react';
import { Check, RefreshCw, SlidersHorizontal, ArrowLeft, GitCompare, Sparkles } from 'lucide-react';
import UniversalCanvas from '@/components/canvas/UniversalCanvas';
import AdaptationPreview from '@/components/universal/AdaptationPreview';
import { computeAdaptation, GUIDED_STRATEGY_CHOICES, analyseCoverCompatibility } from '@/lib/adaptation';
import { pieceToLayer, layerImageMap, regionForPiece } from '@/lib/canvasDemo';
import { useExperienceMode } from '@/lib/ExperienceMode';

export default function FitPreview({ pieces, focalId, design, cover, strategy, onStrategy, onAdjust, onAnotherCover, onCompare, advanced }) {
  const layerImages = useMemo(() => layerImageMap(pieces), [pieces]);
  const layers = useMemo(() => pieces.map(p => pieceToLayer(p, focalId)), [pieces, focalId]);
  const adaptation = useMemo(() => cover ? computeAdaptation({ design, layers, cover, strategy, mirror: 'none' }) : null, [design, layers, cover, strategy]);
  const comp = useMemo(() => cover ? analyseCoverCompatibility({ design, cover }) : null, [design, cover]);
  if (!cover) return null;

  return (
    <div className="space-y-3">
      <div className="panel-glass flex flex-wrap items-center justify-between gap-2 px-3 py-2.5">
        <p className="flex items-center gap-2 text-sm font-semibold text-emerald-200"><Check size={16} /> We fitted your design to this cover</p>
        <span className="text-[10px] text-slate-500">{cover.name} · {cover.limbType} · {cover.side}</span>
      </div>

      <div className="grid gap-3 lg:grid-cols-2">
        {/* LEFT — Universal Master Design (read-only) */}
        <div>
          <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">Universal Master Design</p>
          <UniversalCanvas pieces={pieces} focalId={focalId} readOnly showRegions={false} advanced={advanced} />
        </div>
        {/* RIGHT — Fitted Cover Preview */}
        <div>
          <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-cyan-300">Fitted Cover Preview</p>
          <AdaptationPreview cover={cover} adaptation={adaptation} layerImages={layerImages} demo />
        </div>
      </div>

      {/* Fit strategies */}
      <div className="panel p-3">
        <p className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-slate-400">Fit strategy</p>
        <div className="flex flex-wrap gap-1.5">
          {GUIDED_STRATEGY_CHOICES.map(([k, label]) => (
            <button key={k} onClick={() => onStrategy(k)} className={`rounded-lg border px-3 py-1.5 text-xs font-medium transition ${strategy === k ? 'border-cyan-400/60 bg-cyan-400/15 text-cyan-100' : 'border-white/10 text-slate-300 hover:border-cyan-400/40'}`}>{label}</button>
          ))}
        </div>
        {adaptation && (
          <ul className="mt-3 grid gap-1 sm:grid-cols-2">
            {adaptation.details.map((d, i) => <li key={i} className="flex items-center gap-1.5 text-[11px] text-slate-300"><Check size={11} className="text-emerald-400" /> {d}</li>)}
          </ul>
        )}
        {advanced && adaptation && (
          <div className="mt-3 grid gap-1.5 border-t border-white/10 pt-2 text-[10px] text-slate-400 sm:grid-cols-2">
            <span>Anchor: U {adaptation.anchor.u.toFixed(2)} · V {adaptation.anchor.v.toFixed(2)}</span>
            <span>Decoration rect: {adaptation.decorationRect.x.toFixed(2)},{adaptation.decorationRect.y.toFixed(2)} {adaptation.decorationRect.w.toFixed(2)}×{adaptation.decorationRect.h.toFixed(2)}</span>
            <span>Preserve aspect: {String(adaptation.distortionReport.preserveAspect)}</span>
            <span>Max scale: {adaptation.distortionReport.maxScale}</span>
            <span>Adapted layers: {adaptation.adaptedLayers.length}</span>
            <span>Simulation: {String(adaptation.simulation)}</span>
          </div>
        )}
        <p className="mt-2 text-[10px] text-amber-200">Simulation only — final curved-surface fitting requires the Geometry Engine.</p>
      </div>

      {/* Review actions */}
      <div className="panel-glass flex flex-wrap items-center gap-2 px-3 py-2.5">
        <button className="btn-primary text-sm"><Check size={14} /> Keep this fit</button>
        <button onClick={() => { const i = GUIDED_STRATEGY_CHOICES.findIndex(([k]) => k === strategy); onStrategy(GUIDED_STRATEGY_CHOICES[(i + 1) % GUIDED_STRATEGY_CHOICES.length][0]); }} className="btn-secondary text-sm"><RefreshCw size={14} /> Try another fit</button>
        <button onClick={onAdjust} className="btn-secondary text-sm"><SlidersHorizontal size={14} /> Adjust it</button>
        <button onClick={onAnotherCover} className="btn-secondary text-sm"><ArrowLeft size={14} /> Try another cover</button>
        <button onClick={onCompare} className="btn-ghost text-sm"><GitCompare size={14} /> Compare covers</button>
      </div>
    </div>
  );
}