import { useEffect, useMemo, useState } from "react";
import { useLocation, useParams, Link } from "react-router-dom";
import { fetchLogoTemplates } from "@/services/logoTemplates";
import { Loader2 } from "lucide-react";

// If you already have your real customizer, import it here:
// import { LogoTemplateBuilder } from "@/pages/logo-templates/LogoTemplateBuilder";

type StatePayload = {
  templateId: string;
  name?: string;
  svgUrl?: string;
  rasterUrl?: string;
  defaults?: Record<string, string>;
};

export default function LogoTemplateDetail() {
  const { id = "" } = useParams();
  const location = useLocation();
  const initial = (location.state || {}) as Partial<StatePayload>;

  const [loading, setLoading] = useState(!initial.svgUrl && !initial.rasterUrl);
  const [data, setData] = useState<StatePayload>({
    templateId: initial.templateId || id,
    name: initial.name,
    svgUrl: initial.svgUrl,
    rasterUrl: initial.rasterUrl,
    defaults: initial.defaults,
  });

  // If we didn’t receive the assets via state, fetch by id (works for both collections)
  useEffect(() => {
    if (data.svgUrl || data.rasterUrl) return; // already have it from state
    (async () => {
      try {
        setLoading(true);
        const { items } = await fetchLogoTemplates({ pageSize: 1 }); // fetch first
        // If your service doesn’t fetch by id, add a fetchById helper. For now, scan both collections:
        const all = await Promise.all([
          fetchCollectionDoc("templates", id),
          fetchCollectionDoc("logo_templates", id),
        ]);
        const doc = all.find(Boolean) as any;
        if (doc) {
          setData(d => ({
            ...d,
            name: doc.name,
            svgUrl: doc.downloadURLs?.svg,
            rasterUrl: doc.downloadURLs?.raster,
            defaults: doc.defaults || {},
          }));
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [id]);

  // Once props are known, map to your customizer props here
  const customizerProps = useMemo(() => ({
    templateId: data.templateId,
    name: data.name || data.templateId,
    backgroundSvgUrl: data.svgUrl,          // <— background “logo behind text”
    backgroundRasterUrl: data.rasterUrl,    // fallback
    defaults: data.defaults || {},          // { title, tagline, color, etc. }
  }), [data]);

  return (
    <div className="p-6 space-y-4">
      <Link to="/business-assets/templates/logo-templates" className="text-sm text-muted-foreground hover:underline">
        ← Back to Templates
      </Link>

      <h1 className="text-2xl font-semibold">{customizerProps.name}</h1>

      {loading ? (
        <div className="flex items-center gap-2 text-muted-foreground">
          <Loader2 className="w-4 h-4 animate-spin" /> Loading template…
        </div>
      ) : !customizerProps.backgroundSvgUrl && !customizerProps.backgroundRasterUrl ? (
        <p className="text-red-500">Template assets not found.</p>
      ) : (
        <>
          {/* If you already have your real customizer, render it here and pass props: */}
          {/* <LogoTemplateBuilder {...customizerProps} /> */}

          {/* TEMPORARY PREVIEW so QA can confirm asset + layering works */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div className="relative border rounded-lg bg-white p-8 min-h-[420px] overflow-hidden">
              {customizerProps.backgroundSvgUrl ? (
                <img
                  src={customizerProps.backgroundSvgUrl}
                  alt=""
                  className="absolute inset-0 w-full h-full object-contain opacity-90 pointer-events-none"
                />
              ) : (
                <img
                  src={customizerProps.backgroundRasterUrl!}
                  alt=""
                  className="absolute inset-0 w-full h-full object-contain opacity-90 pointer-events-none"
                />
              )}

              {/* “Text that moves/curves” placeholder — your builder will control these */}
              <div className="relative z-10 flex flex-col items-center justify-center h-full">
                <h2 className="text-4xl font-bold tracking-tight">{customizerProps.defaults?.title || "Your Brand"}</h2>
                <p className="mt-2 text-sm text-muted-foreground">
                  {customizerProps.defaults?.tagline || "Tagline goes here"}
                </p>
              </div>
            </div>

            <div className="space-y-4">
              {/* Controls panel placeholder – hook up to your builder */}
              <div className="border rounded-lg p-4">
                <h3 className="font-medium mb-2">Controls</h3>
                <p className="text-sm text-muted-foreground">
                  This panel will host the sliders/inputs (size, rotation, curve, colors, title, tagline) from your customizer.
                </p>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// ——— helpers ———
import { db } from "@/utils/firebase-templates";
import { doc, getDoc } from "firebase/firestore";

async function fetchCollectionDoc(collectionName: string, id: string) {
  try {
    const snap = await getDoc(doc(db, collectionName, id));
    return snap.exists() ? snap.data() : null;
  } catch {
    return null;
  }
}
