import React, { useMemo, useState } from "react";
import { useBrandKit } from "../../../utils/brand";
import { useLocalStorage } from "../../../hooks/useLocalStorage";
import { Upload, Trash2, Check, ChevronRight } from "lucide-react";
import { fileToDataUrl } from "../../../utils/file";

// Mock galleries (replace with your real sets)
const BODY_LAYOUTS = [
  { id: "title", name: "Title & Content" },
  { id: "two-col", name: "Two Columns" },
  { id: "bullets", name: "Bulleted" },
  { id: "chart", name: "Chart + Notes" },
  { id: "table", name: "Table" },
  { id: "quote", name: "Quote" },
];

const INFOGRAPHICS = [
  { id: "inf-2a", name: "2-Section • Split" , sections: 2 },
  { id: "inf-3a", name: "3-Section • Steps" , sections: 3 },
  { id: "inf-4a", name: "4-Section • Grid" , sections: 4 },
  { id: "inf-6a", name: "6-Section • Icons", sections: 6 },
  { id: "inf-3b", name: "3-Section • Timeline", sections: 3 },
  { id: "inf-4b", name: "4-Section • Compare", sections: 4 },
];

type Size = "16x9" | "4x3";

export default function PresentationTemplate() {
  const brand = useBrandKit();

  // Template config (persist locally so user doesn’t lose progress)
  const [size, setSize] = useLocalStorage<Size>("pt.size", "16x9");
  const [logo, setLogo] = useLocalStorage<string | null>("pt.logo", brand.logo?.dataUrl || null);
  const [fonts, setFonts] = useLocalStorage("pt.fonts", {
    heading: brand.fonts?.heading || "Inter",
    body: brand.fonts?.body || "Inter",
  });
  const [accents, setAccents] = useLocalStorage<string[]>("pt.accents", [
    brand.colors.primary || "#0ea5e9",
    brand.colors.accent || "#f99f1b",
    brand.colors.neutral || "#64748b",
    "#8b5cf6",
    "#22c55e",
    "#ef4444",
  ]);

  const [layouts, setLayouts] = useLocalStorage<string[]>("pt.layouts", ["title", "two-col", "bullets"]);
  const [infoPages, setInfoPages] = useLocalStorage<string[]>("pt.infopages", ["inf-3a", "inf-4a"]);

  // derived
  const canGenerate = useMemo(
    () => accents.filter(Boolean).length >= 2 && layouts.length > 0,
    [accents, layouts]
  );

  async function onPickLogo(e: React.ChangeEvent<HTMLInputElement>) {
    const f = e.target.files?.[0];
    if (!f) return;
    setLogo(await fileToDataUrl(f));
  }

  function removeLogo() { setLogo(null); }

  function toggleItem(id: string, list: string[], setList: (v: string[]) => void) {
    setList(list.includes(id) ? list.filter((x) => x !== id) : [...list, id]);
  }

  function changeAccent(idx: number, color: string) {
    const next = [...accents];
    next[idx] = color;
    setAccents(next);
  }

  function resetAccents() {
    setAccents([
      brand.colors.primary || "#0ea5e9",
      brand.colors.accent || "#f99f1b",
      brand.colors.neutral || "#64748b",
      "#8b5cf6",
      "#22c55e",
      "#ef4444",
    ]);
  }

  function buildConfig() {
    return {
      size,
      brand: {
        name: brand.name,
        logo,
        fonts,
        accents,
      },
      selections: {
        layouts,
        infographics: infoPages,
      },
    };
  }

  function saveConfigLocally() {
    const cfg = buildConfig();
    localStorage.setItem("pt.lastBuild", JSON.stringify(cfg));
    alert("Saved! Ready for export step.");
  }

  async function generateTemplate() {
    saveConfigLocally();

    // 🔌 Backend hook (enable when ready)
    // const res = await fetch("/api/ppt/build-template", {
    //   method: "POST",
    //   headers: { "Content-Type": "application/json" },
    //   body: JSON.stringify(buildConfig()),
    // });
    // if (!res.ok) { const j = await res.json().catch(()=>({})); alert(j.error || "Build failed"); return; }
    // const { fileUrl } = await res.json(); // e.g., signed URL
    // window.location.href = fileUrl;

    // For now: we just confirm it saved
    console.log("PT config", buildConfig());
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Presentation Template</h1>
        <div className="flex items-center gap-2">
          <button
            onClick={saveConfigLocally}
            className="px-4 py-2 rounded-lg border border-white/10 hover:bg-white/5"
          >
            Save Settings
          </button>
          <button
            onClick={generateTemplate}
            disabled={!canGenerate}
            className={`px-4 py-2 rounded-lg ${canGenerate ? "bg-emerald-600 hover:bg-emerald-700 text-white" : "bg-slate-700 text-slate-300 cursor-not-allowed"}`}
          >
            Generate Template
          </button>
        </div>
      </div>

      <div className="grid xl:grid-cols-[360px,1fr] gap-6">
        {/* Branding side panel */}
        <aside className="rounded-xl border border-white/10 bg-slate-900/60 p-4">
          <div className="text-sm text-slate-400">Brand Panel</div>

          {/* Logo */}
          <div className="mt-3">
            <div className="text-xs text-slate-400 mb-1">Logo</div>
            {logo ? (
              <div className="relative rounded-lg border border-white/10 bg-slate-950/60 p-2">
                <img src={logo} alt="logo" className="max-h-20 object-contain mx-auto" />
                <button
                  className="absolute top-2 right-2 p-1.5 rounded bg-rose-600 text-white hover:bg-rose-700"
                  onClick={removeLogo}
                  title="Remove logo"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            ) : (
              <label className="block">
                <input type="file" accept="image/*" onChange={onPickLogo} className="hidden" />
                <div className="cursor-pointer inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-white/10 hover:bg-white/5">
                  <Upload className="w-4 h-4" /> Upload Logo
                </div>
              </label>
            )}
            {logo && (
              <a
                href={logo}
                download="brand-logo"
                className="mt-2 inline-block text-xs text-sky-400 hover:underline"
              >
                Download logo asset
              </a>
            )}
          </div>

          {/* Fonts */}
          <div className="mt-4">
            <div className="text-xs text-slate-400 mb-1">Fonts</div>
            <div className="grid grid-cols-1 gap-2">
              <div>
                <label className="text-xs text-slate-400">Heading</label>
                <input
                  value={fonts.heading}
                  onChange={(e) => setFonts({ ...fonts, heading: e.target.value })}
                  className="mt-1 w-full rounded-lg bg-slate-950/60 border border-white/10 p-2 text-slate-100"
                />
              </div>
              <div>
                <label className="text-xs text-slate-400">Body</label>
                <input
                  value={fonts.body}
                  onChange={(e) => setFonts({ ...fonts, body: e.target.value })}
                  className="mt-1 w-full rounded-lg bg-slate-950/60 border border-white/10 p-2 text-slate-100"
                />
              </div>
            </div>
            <p className="mt-2 text-[11px] text-slate-400">
              Text colors remain black/white automatically for readability.
            </p>
          </div>

          {/* Accent colors */}
          <div className="mt-4">
            <div className="text-xs text-slate-400 mb-1">Accent Colors (6)</div>
            <div className="grid grid-cols-3 gap-2">
              {accents.map((c, i) => (
                <label key={i} className="flex items-center gap-2 rounded-lg border border-white/10 p-2">
                  <input
                    type="color"
                    value={c}
                    onChange={(e) => changeAccent(i, e.target.value)}
                    className="h-7 w-7 bg-transparent"
                  />
                  <span className="text-xs text-slate-300">{c.toUpperCase()}</span>
                </label>
              ))}
            </div>
            <button onClick={resetAccents} className="mt-2 text-xs text-sky-400 hover:underline">
              Reset to brand defaults
            </button>
          </div>

          {/* Size */}
          <div className="mt-4">
            <div className="text-xs text-slate-400 mb-1">Template Size</div>
            <div className="flex gap-2">
              {(["16x9", "4x3"] as Size[]).map((s) => (
                <button
                  key={s}
                  onClick={() => setSize(s)}
                  className={`px-3 py-1.5 rounded-lg border text-sm ${
                    size === s ? "bg-white/10 border-white/20" : "border-white/10 hover:bg-white/5"
                  }`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        </aside>

        {/* Main builder */}
        <section className="space-y-6">
          {/* Body layouts */}
          <div className="rounded-xl border border-white/10 bg-slate-900/60 p-5">
            <div className="flex items-center justify-between mb-3">
              <h2 className="text-lg font-semibold">Body Layouts</h2>
              <span className="text-xs text-slate-400">{layouts.length} selected</span>
            </div>
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {BODY_LAYOUTS.map((item) => {
                const active = layouts.includes(item.id);
                return (
                  <button
                    key={item.id}
                    onClick={() => toggleItem(item.id, layouts, setLayouts)}
                    className={`relative text-left rounded-lg border p-3 ${active ? "border-emerald-500/50 bg-emerald-500/5" : "border-white/10 hover:bg-white/5"}`}
                  >
                    <div className="flex items-start justify-between">
                      <div>
                        <div className="font-medium text-white">{item.name}</div>
                        <div className="text-xs text-slate-400">{item.id}</div>
                      </div>
                      {active && <Check className="w-4 h-4 text-emerald-400" />}
                    </div>
                    <div className="mt-2 h-20 rounded bg-slate-950/60 border border-white/10" />
                  </button>
                );
              })}
            </div>
          </div>

          {/* Infographic pages */}
          <div className="rounded-xl border border-white/10 bg-slate-900/60 p-5">
            <div className="flex items-center justify-between mb-3">
              <h2 className="text-lg font-semibold">Infographics</h2>
              <span className="text-xs text-slate-400">{infoPages.length} selected</span>
            </div>
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {INFOGRAPHICS.map((item) => {
                const active = infoPages.includes(item.id);
                return (
                  <button
                    key={item.id}
                    onClick={() => toggleItem(item.id, infoPages, setInfoPages)}
                    className={`relative text-left rounded-lg border p-3 ${active ? "border-sky-500/50 bg-sky-500/5" : "border-white/10 hover:bg-white/5"}`}
                  >
                    <div className="flex items-start justify-between">
                      <div>
                        <div className="font-medium text-white">{item.name}</div>
                        <div className="text-xs text-slate-400">{item.sections} sections</div>
                      </div>
                      {active && <Check className="w-4 h-4 text-sky-400" />}
                    </div>
                    <div className="mt-2 h-20 rounded bg-slate-950/60 border border-white/10" />
                  </button>
                );
              })}
            </div>
            <p className="mt-3 text-xs text-slate-400">
              You can also choose infographic pages directly in the Infographics section and send them here.
            </p>
          </div>

          {/* Next step hint */}
          <div className="rounded-xl border border-white/10 bg-slate-900/60 p-4 flex items-center justify-between">
            <div className="text-sm text-slate-300">
              Ready? Click <b>Generate Template</b> and we’ll assemble your PPT master using your brand panel and selections.
            </div>
            <ChevronRight className="w-5 h-5 text-slate-400" />
          </div>
        </section>
      </div>
    </div>
  );
}
