import { useEffect, useState, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowRight, ArrowLeft, Loader2, Save, RefreshCw, Sliders, Check, ShieldCheck, AlertTriangle, Box } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import { Image as ContentImage } from '@/components/ui/image';
import AdaptationPreview from '@/components/universal/AdaptationPreview';
import { analyseCoverCompatibility, computeAdaptation, GUIDED_STRATEGY_CHOICES } from '@/lib/adaptation';

const compatTone = { good: 'border-emerald-400/40 bg-emerald-400/10 text-emerald-200', adaptable: 'border-cyan-400/40 bg-cyan-400/10 text-cyan-200', limited: 'border-amber-400/40 bg-amber-400/10 text-amber-200', requires_processing: 'border-violet-400/40 bg-violet-400/10 text-violet-200' };
const compatLabel = { good: 'Good match', adaptable: 'Can be adapted', limited: 'Limited space', requires_processing: 'Requires 3D processing' };

export default function FitDesign() {
  const [params] = useSearchParams();
  const designId = params.get('design');
  const initialCover = params.get('cover');
  const navigate = useNavigate();
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';

  const [design, setDesign] = useState(null);
  const [layers, setLayers] = useState([]);
  const [assets, setAssets] = useState([]);
  const [covers, setCovers] = useState([]);
  const [coverId, setCoverId] = useState(initialCover || null);
  const [strategy, setStrategy] = useState('best_fit');
  const [mirror, setMirror] = useState('none');
  const [busy, setBusy] = useState(false);
  const [phase, setPhase] = useState('choose'); // choose | review | saved
  const [error, setError] = useState(null);
  const [savedVariant, setSavedVariant] = useState(null);

  useEffect(() => {
    Promise.all([
      base44.entities.UniversalDesign.get(designId).catch(() => null),
      base44.entities.UniversalDesignLayer.filter({ universalDesignId: designId }).catch(() => []),
      base44.entities.ArtworkAsset.filter({ projectId: designId }).catch(() => []),
      base44.entities.CoverModel.filter({ active: true, validationStatus: 'validated' }).catch(() => [])
    ]).then(([d, l, a, c]) => {
      setDesign(d); setLayers(Array.isArray(l) ? l : []); setAssets(Array.isArray(a) ? a : []); setCovers(Array.isArray(c) ? c : []);
      if (!coverId && Array.isArray(c) && c.length) setCoverId(c[0].id);
    });
  }, [designId]);

  const cover = useMemo(() => covers.find(c => c.id === coverId) || null, [covers, coverId]);
  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 compatibility = useMemo(() => cover ? analyseCoverCompatibility({ design, cover, geometryAvailable: false }) : null, [design, cover]);
  const adaptation = useMemo(() => (cover && layers.length) ? computeAdaptation({ design, layers, cover, strategy, mirror }) : null, [design, layers, cover, strategy, mirror]);

  const fit = async () => {
    if (!cover || !adaptation) return;
    setBusy(true); setError(null);
    try {
      await base44.integrations.Core.createAdaptationPreview({ universalDesignId: designId, coverModelId: cover.id, strategy });
      setPhase('review');
    } catch { setError('Could not build the adaptation preview.'); }
    finally { setBusy(false); }
  };

  const keep = async () => {
    if (!cover || !adaptation) return;
    setBusy(true); setError(null);
    try {
      const me = await base44.auth.me();
      const v = await base44.entities.CoverDesignVariant.create({
        name: `${design?.name || 'Design'} → ${cover.name}`,
        owner: me.id,
        universalDesignId: designId,
        universalDesignVersion: design?.version || 1,
        coverModelId: cover.id,
        status: 'adapted_preview',
        adaptationStrategy: strategy,
        adaptationVersion: 1,
        adaptationStatus: 'preview_ready',
        browserPreviewStatus: 'ready',
        geometryEngineStatus: 'not_submitted',
        targetLimbType: cover.limbType,
        targetSide: cover.side,
        coverVersion: cover.version || '1',
        adaptedLayerData: { strategy, mirror, layers: adaptation.adaptedLayers, decorationRect: adaptation.decorationRect },
        sourceMasterLayerData: { version: design?.version || 1 },
        focalPointResults: adaptation.focalPointResults,
        distortionReport: adaptation.distortionReport,
        clippedRegions: adaptation.clippedRegions,
        repeatedRegions: adaptation.repeatedRegions,
        movedRegions: adaptation.movedRegions,
        protectedZoneWarnings: adaptation.protectedZoneWarnings,
        brandingStatus: adaptation.brandingStatus,
        mirrorMode: mirror,
        previewImageUrl: design?.masterPreviewImageUrl,
        shireVaultPath: `/SHiRELimbs/CoverCanvas/Variants/${Date.now()}`,
        summary: adaptation.summary,
        adaptationDetails: adaptation.details
      });
      setSavedVariant(v);
      setPhase('saved');
    } catch (e) { setError(`Could not save the fitted version. ${e?.message || ''}`); }
    finally { setBusy(false); }
  };

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

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Fit your design to a cover' : 'Adaptation · Fit to cover'}
        title="Choose where this design will go"
        description="Your universal design stays safe. Fitting it creates a new cover-specific version — the original is never changed."
      />

      {error && <div className="warning-box mb-4">{error}</div>}

      <div className="grid gap-5 xl:grid-cols-[1fr_1.1fr]">
        {/* Cover selection */}
        <section className="panel h-fit">
          <h2 className="section-title"><Box size={16} className="text-cyan-300" />Choose a validated cover</h2>
          <div className="grid max-h-[460px] grid-cols-2 gap-2 overflow-y-auto pr-1">
            {covers.length === 0 && <div className="empty col-span-2">No validated covers. Import one in the Cover Library first.</div>}
            {covers.map(c => (
              <button key={c.id} onClick={() => { setCoverId(c.id); setPhase('choose'); }} className={`overflow-hidden rounded-xl border text-left transition ${coverId === c.id ? 'border-cyan-400/60 bg-cyan-400/[0.08]' : 'border-white/10 hover:border-cyan-400/30'}`}>
                <div className="aspect-[4/3] overflow-hidden viewport-grid">
                  {c.previewImageUrl ? <ContentImage src={c.previewImageUrl} alt={c.name} fittingType="fill" className="h-full w-full" /> : <div className="grid h-full place-items-center text-slate-500"><Box size={20} className="text-cyan-400/40" /></div>}
                </div>
                <div className="p-2">
                  <p className="truncate text-xs font-semibold text-white">{c.name}</p>
                  <p className="text-[10px] text-slate-500">{c.limbType} · {c.side}</p>
                </div>
              </button>
            ))}
          </div>
        </section>

        {/* Adaptation */}
        <section className="panel">
          {!cover ? (
            <div className="empty">Select a cover to see how your design fits.</div>
          ) : (
            <>
              <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
                <h2 className="section-title mb-0"><Sliders size={16} className="text-cyan-300" />Adaptation</h2>
                {compatibility && <span className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-semibold ${compatTone[compatibility.level]}`}>{compatLabel[compatibility.level]}</span>}
              </div>

              {phase !== 'saved' && adaptation && (
                <AdaptationPreview cover={cover} adaptation={adaptation} layerImages={layerImages} />
              )}

              {phase === 'saved' && savedVariant && (
                <div className="rounded-xl border border-emerald-400/30 bg-emerald-400/[0.08] p-4 text-center">
                  <Check size={28} className="mx-auto mb-2 text-emerald-300" />
                  <h3 className="font-heading text-lg font-semibold text-white">Fitted version saved</h3>
                  <p className="mt-1 text-sm text-slate-300">{savedVariant.summary}</p>
                  <p className="mt-1 text-[11px] text-slate-500">Your universal design was not changed.</p>
                  <div className="mt-4 flex flex-wrap justify-center gap-2">
                    <button onClick={() => navigate('/cover-variants')} className="btn-primary">View cover variants <ArrowRight size={15} /></button>
                    <button onClick={() => { setPhase('choose'); setSavedVariant(null); }} className="btn-ghost">Fit another cover</button>
                  </div>
                </div>
              )}

              {phase === 'choose' && (
                <>
                  <div className="mt-4">
                    <p className="mb-2 text-xs font-semibold uppercase tracking-wider text-slate-400">Fit style</p>
                    <div className="flex flex-wrap gap-2">
                      {GUIDED_STRATEGY_CHOICES.map(([k, t]) => (
                        <button key={k} onClick={() => setStrategy(k)} className={`chip ${strategy === k ? 'chip-active' : ''}`}>{t}</button>
                      ))}
                    </div>
                  </div>
                  <div className="mt-3">
                    <p className="mb-2 text-xs font-semibold uppercase tracking-wider text-slate-400">Side adaptation</p>
                    <div className="flex flex-wrap gap-2">
                      {[['none', 'Keep orientation'], ['mirror', 'Mirror entire design'], ['smart', 'Smart mirror']].map(([k, t]) => (
                        <button key={k} onClick={() => setMirror(k)} className={`chip ${mirror === k ? 'chip-active' : ''}`}>{t}</button>
                      ))}
                    </div>
                    {mirror !== 'none' && <p className="mt-1 text-[11px] text-amber-200">Text will be kept readable under smart mirror — confirm in the review step.</p>}
                  </div>

                  {compatibility && (
                    <div className="mt-4 rounded-lg border border-white/[0.06] bg-black/20 p-3 text-xs text-slate-300">
                      <p className="mb-1 font-semibold text-slate-200">Compatibility</p>
                      <ul className="list-disc space-y-0.5 pl-4">{compatibility.reasons.map((r, i) => <li key={i}>{r}</li>)}</ul>
                    </div>
                  )}

                  <button disabled={busy} onClick={fit} className="btn-primary mt-4 w-full">{busy ? <Loader2 size={15} className="animate-spin" /> : <Sliders size={15} />} Build adaptation preview</button>
                </>
              )}

              {phase === 'review' && adaptation && (
                <>
                  <div className="mt-4 rounded-lg border border-cyan-400/20 bg-cyan-400/[0.06] p-3 text-sm text-cyan-100">
                    <p className="font-semibold">{adaptation.summary}</p>
                    {adaptation.details.length > 0 && (
                      <ul className="mt-2 list-disc space-y-0.5 pl-4 text-[12px] text-slate-300">{adaptation.details.map((d, i) => <li key={i}>{d}</li>)}</ul>
                    )}
                  </div>
                  <div className="mt-4 flex flex-wrap gap-2">
                    <button disabled={busy} onClick={keep} className="btn-primary flex-1">{busy ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />} Keep this fit</button>
                    <button onClick={() => setPhase('choose')} className="btn-secondary"><RefreshCw size={14} /> Try another fit</button>
                  </div>
                  <p className="mt-2 flex items-center gap-1 text-[11px] text-slate-500"><ShieldCheck size={11} />This preview shows intended fit only. Final surface wrapping happens during 3D processing.</p>
                </>
              )}
            </>
          )}
        </section>
      </div>

      <div className="mt-6 flex justify-between">
        <button onClick={() => navigate('/designs')} className="btn-ghost"><ArrowLeft size={15} /> Back to designs</button>
        {phase !== 'saved' && <button onClick={() => navigate('/cover-variants')} className="tool-button">View all variants</button>}
      </div>
    </>
  );
}