// src/pages/BrandKit/BrandKitPage.tsx
import React, { useMemo, useState } from "react";
import { LogoCard } from "../../components/LogoCard";
import { ColorSwatch } from "../../components/ColorSwatch";
import {
  rollAll,
  rollOne,
  type Palette,
  type PaletteKey,
  type PalettePreset,
  applyPresetToPalette,
  rollWithinPreset,
} from "../../services/brand/palette";
import { makePngLogo } from "../../utils/pngLogo";

// ---- Types & Stubs (wire to your backend as needed) ----
type StylePack = "balanced" | "monogram" | "badge";
type MarkMode = "auto" | "wordmark" | "icon";
type LogoMode = "textIcon_svg" | "imageText_png";

type GeneratedLogo = {
  id: string;
  filename: string;
  svg?: string;
  url?: string;           // for raster (PNG data URL)
  kind: "svg" | "png";
};

// Example generator: returns either SVG set or PNG+wordmark set.
async function generateBrandAssets(args: {
  name: string;
  industry: string;
  tone: string;
  palette: Palette;
  stylePack: StylePack;
  markMode: MarkMode;
  logoMode: LogoMode;
  prompt?: string;        // only used for imageText_png mode
}): Promise<{ logos: GeneratedLogo[] }> {
  if (args.logoMode === "imageText_png") {
    // PNG mark (data URL) + a couple variants
    const png = await makePngLogo({
      name: args.name,
      bg: args.palette.primary,
      fg: args.palette.surface,
      prompt: args.prompt,
      badge: true,
    });

    // simple secondary with accent
    const pngAccent = await makePngLogo({
      name: args.name,
      bg: args.palette.accent,
      fg: args.palette.surface,
      prompt: args.prompt,
      badge: true,
    });

    return {
      logos: [
        { id: "p1", filename: "logo-image-primary.png", url: png, kind: "png" },
        { id: "p2", filename: "logo-image-accent.png", url: pngAccent, kind: "png" },
      ],
    };
  }

  // Default SVG text+icon set (placeholder)
  const svg1 = `<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="${args.palette.primary}"/><text x="50%" y="54%" font-size="140" font-family="Inter, Arial" fill="${args.palette.surface}" text-anchor="middle" dominant-baseline="middle">${args.name[0] ?? "A"}</text></svg>`;
  const svg2 = `<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="${args.palette.surface}"/><circle cx="256" cy="256" r="180" fill="${args.palette.primary}"/></svg>`;
  const svg3 = `<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" rx="64" fill="${args.palette.accent}"/><text x="50%" y="52%" font-size="200" font-family="Inter, Arial" fill="${args.palette.surface}" text-anchor="middle" dominant-baseline="middle">Aa</text></svg>`;

  return {
    logos: [
      { id: "s1", filename: "logo-primary.svg", svg: svg1, kind: "svg" },
      { id: "s2", filename: "logo-reverse.svg", svg: svg2, kind: "svg" },
      { id: "s3", filename: "logo-mark.svg", svg: svg3, kind: "svg" },
    ],
  };
}

// Optional: call your existing zip API instead. Here we download one-by-one.
async function downloadAllAssets(logos: GeneratedLogo[]) {
  for (const logo of logos) {
    if (logo.kind === "svg" && logo.svg) {
      const blob = new Blob([logo.svg], { type: "image/svg+xml;charset=utf-8" });
      const a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      a.download = logo.filename || "logo.svg";
      a.click();
      URL.revokeObjectURL(a.href);
    } else if (logo.kind === "png" && logo.url) {
      const res = await fetch(logo.url);
      const blob = await res.blob();
      const a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      a.download = logo.filename || "logo.png";
      a.click();
      URL.revokeObjectURL(a.href);
    }
    await new Promise((r) => setTimeout(r, 60));
  }
}

// ---- Component ----
export default function BrandKitPage() {
  // Stepper
  const [step, setStep] = useState<1 | 2 | 3>(1);

  // Step 1 — Basics
  const [name, setName] = useState("Cafe DuMonte");
  const [industry, setIndustry] = useState("restaurant");
  const [tone, setTone] = useState("Modern");
  const [stylePack, setStylePack] = useState<StylePack>("balanced");
  const [markMode, setMarkMode] = useState<MarkMode>("auto");

  // Step 2 — Colors
  const [palette, setPalette] = useState<Palette>({
    primary: "#4274b9",
    secondary: "#b94c42",
    accent: "#42afb9",
    neutral: "#f3f4f6",
    surface: "#ffffff",
    text: "#1f2937",
  });
  const [locks, setLocks] = useState<Record<PaletteKey, boolean>>({
    primary: false, secondary: false, accent: false, neutral: true, surface: true, text: true,
  });
  const [preset, setPreset] = useState<PalettePreset>("warm");

  // Step 3 — Logo mode
  const [logoMode, setLogoMode] = useState<LogoMode>("textIcon_svg");
  const [iconPrompt, setIconPrompt] = useState("simple geometric coffee cup, friendly, minimal"); // for imageText_png

  // Output
  const [logos, setLogos] = useState<GeneratedLogo[]>([]);
  const canNextFrom1 = name.trim().length > 1;

  // Color helpers
  const rollAllUnlocked = () => {
    const all = rollAll(palette);
    const next: Palette = { ...palette };
    (Object.keys(next) as PaletteKey[]).forEach((k) => {
      if (!locks[k]) next[k] = (all as any)[k];
    });
    setPalette(next);
  };
  const rollSingle = (key: PaletteKey) => { if (!locks[key]) setPalette((p) => rollOne(p, key)); };
  const toggleLock = (key: PaletteKey) => setLocks((l) => ({ ...l, [key]: !l[key] }));
  const lockAll = () => setLocks({ primary: true, secondary: true, accent: true, neutral: true, surface: true, text: true });
  const unlockAll = () => setLocks({ primary: false, secondary: false, accent: false, neutral: false, surface: false, text: false });

  const applyPreset = () => setPalette((p) => applyPresetToPalette(preset, p, locks));
  const rollPreset = () => setPalette((p) => rollWithinPreset(preset, p, locks));

  // Generate
  const generate = async () => {
    const res = await generateBrandAssets({
      name, industry, tone, palette, stylePack, markMode, logoMode,
      prompt: logoMode === "imageText_png" ? iconPrompt : undefined,
    });
    setLogos(res.logos);
    setStep(3);
    setTimeout(() => {
      document.getElementById("logos-section")?.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 20);
  };

  // UI helpers
  const paletteEntries: { key: PaletteKey; label: string }[] = useMemo(() => ([
    { key: "primary", label: "Primary" },
    { key: "secondary", label: "Secondary" },
    { key: "accent", label: "Accent" },
    { key: "neutral", label: "Neutral" },
    { key: "surface", label: "Surface" },
    { key: "text", label: "Text" },
  ]), []);

  return (
    <div className="max-w-6xl mx-auto p-4 md:p-6">
      <h1 className="text-2xl md:text-3xl font-semibold mb-4">Brand Kit Generator</h1>

      {/* Stepper */}
      <div className="flex items-center gap-3 mb-6">
        {([1,2,3] as const).map((n) => (
          <button
            key={n}
            className={`px-3 py-1.5 rounded-full text-sm border ${step===n?'bg-neutral-900 text-white border-neutral-900':'bg-white text-neutral-700 hover:bg-neutral-50'}`}
            onClick={() => setStep(n)}
            aria-current={step===n? 'step' : undefined}
          >
            Step {n}
          </button>
        ))}
        <div className="text-sm text-neutral-500">1) Basics → 2) Colors → 3) Logo & Generate</div>
      </div>

      {/* -------- STEP 1 -------- */}
      {step === 1 && (
        <section className="space-y-4">
          <div className="grid md:grid-cols-3 gap-3">
            <input className="px-3 py-2 rounded-md border" value={name} onChange={(e)=>setName(e.target.value)} placeholder="Brand name" />
            <input className="px-3 py-2 rounded-md border" value={industry} onChange={(e)=>setIndustry(e.target.value)} placeholder="Industry (e.g., restaurant)" />
            <select className="px-3 py-2 rounded-md border" value={tone} onChange={(e)=>setTone(e.target.value)}>
              <option>Modern</option><option>Classic</option><option>Playful</option><option>Luxury</option>
            </select>
          </div>

          <div className="grid md:grid-cols-3 gap-3">
            <select className="px-3 py-2 rounded-md border" value={stylePack} onChange={(e)=>setStylePack(e.target.value as StylePack)}>
              <option value="balanced">Balanced (Geometric + Monogram + Badge)</option>
              <option value="monogram">Monogram-focused (3x)</option>
              <option value="badge">Badge-focused (3x)</option>
            </select>
            <select className="px-3 py-2 rounded-md border" value={markMode} onChange={(e)=>setMarkMode(e.target.value as MarkMode)}>
              <option value="auto">Auto</option>
              <option value="wordmark">Keep wordmark</option>
              <option value="icon">Icon-only</option>
            </select>
          </div>

          <div className="pt-2">
            <button disabled={!canNextFrom1} onClick={()=>setStep(2)} className={`px-4 py-2 rounded-lg ${canNextFrom1?'bg-emerald-600 hover:bg-emerald-700 text-white':'bg-neutral-200 text-neutral-500 cursor-not-allowed'}`}>
              Next: Colors →
            </button>
          </div>
        </section>
      )}

      {/* -------- STEP 2 -------- */}
      {step === 2 && (
        <section className="space-y-4">
          {/* Preset row */}
          <div className="flex flex-wrap items-center gap-2">
            <label className="text-sm text-neutral-700">Palette Preset</label>
            <select
              value={preset}
              onChange={(e)=>setPreset(e.target.value as PalettePreset)}
              className="px-3 py-1.5 rounded-md border"
            >
              <option value="warm">Warm</option>
              <option value="cool">Cool</option>
              <option value="earth">Earth Tones</option>
              <option value="sepia">Sepia / Vintage</option>
              <option value="pastel">Pastel</option>
              <option value="neon">Neon</option>
            </select>

            <button onClick={applyPreset} className="px-3 py-1.5 rounded-md border hover:bg-neutral-50">Apply Preset</button>
            <button onClick={rollPreset} className="px-3 py-1.5 rounded-md border hover:bg-neutral-50">🎲 Roll within preset</button>

            <span className="mx-2 h-5 w-px bg-neutral-300" />

            <button onClick={rollAllUnlocked} className="px-3 py-1.5 rounded-md border hover:bg-neutral-50">🎲 Roll all unlocked</button>
            <button onClick={()=>setLocks({ primary:true,secondary:true,accent:true,neutral:true,surface:true,text:true })} className="px-3 py-1.5 rounded-md border hover:bg-neutral-50">📌 Lock all</button>
            <button onClick={()=>setLocks({ primary:false,secondary:false,accent:false,neutral:false,surface:false,text:false })} className="px-3 py-1.5 rounded-md border hover:bg-neutral-50">🔓 Unlock all</button>

            <div className="text-xs text-neutral-500 ml-2">Locks are respected by preset & rolls.</div>
          </div>

          <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-4">
            {paletteEntries.map(({key, label}) => (
              <ColorSwatch
                key={key}
                label={label}
                hex={palette[key]}
                locked={locks[key]}
                onChange={(v)=>setPalette((p)=>({ ...p, [key]: v }))}
                onRoll={()=>rollSingle(key)}
                onToggleLock={()=>toggleLock(key)}
              />
            ))}
          </div>

          <div className="flex items-center gap-2 pt-2">
            <button onClick={()=>setStep(1)} className="px-3 py-2 rounded-lg border hover:bg-neutral-50">← Back</button>
            <button onClick={()=>setStep(3)} className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white">Next: Logo options →</button>
          </div>
        </section>
      )}

      {/* -------- STEP 3 -------- */}
      {step === 3 && (
        <section className="space-y-5">
          <div className="grid md:grid-cols-3 gap-3 items-start">
            {/* Logo mode & controls */}
            <div className="rounded-xl border bg-white p-3 space-y-3">
              <div className="text-sm font-semibold">Logo Output</div>
              <div className="flex flex-col gap-2 text-sm">
                <label className="flex items-center gap-2">
                  <input type="radio" checked={logoMode==="textIcon_svg"} onChange={()=>setLogoMode("textIcon_svg")} />
                  Text + Icon (SVG vector)
                </label>
                <label className="flex items-center gap-2">
                  <input type="radio" checked={logoMode==="imageText_png"} onChange={()=>setLogoMode("imageText_png")} />
                  Image + Text (PNG raster)
                </label>
              </div>

              {logoMode === "imageText_png" && (
                <div className="space-y-2">
                  <div className="text-xs text-neutral-500">Describe the image/icon you want (used by the image generator):</div>
                  <textarea className="w-full min-h-[100px] px-3 py-2 rounded-md border text-sm" value={iconPrompt} onChange={(e)=>setIconPrompt(e.target.value)} />
                  <div className="text-[11px] text-neutral-500">Note: this preview uses a local PNG stub; wire to your AI image API to honor prompts fully.</div>
                </div>
              )}

              <div className="flex items-center gap-2 pt-1">
                <button onClick={()=>setStep(2)} className="px-3 py-2 rounded-lg border hover:bg-neutral-50">← Back</button>
              </div>
            </div>

            {/* Palette preview */}
            <div className="rounded-xl border bg-white p-3">
              <div className="text-sm font-semibold mb-2">Palette</div>
              <div className="grid grid-cols-3 gap-2">
                {Object.entries(palette).map(([k, v])=>(
                  <div key={k} className="rounded-lg border overflow-hidden">
                    <div className="h-12" style={{ background: v }} />
                    <div className="p-2 text-xs flex items-center justify-between">
                      <span className="capitalize">{k}</span>
                      <span className="font-mono">{v}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Summary */}
            <div className="rounded-xl border bg-white p-3">
              <div className="text-sm font-semibold mb-2">Summary</div>
              <dl className="text-sm space-y-1">
                <div className="flex justify-between"><dt className="text-neutral-500">Name</dt><dd>{name}</dd></div>
                <div className="flex justify-between"><dt className="text-neutral-500">Industry</dt><dd>{industry}</dd></div>
                <div className="flex justify-between"><dt className="text-neutral-500">Tone</dt><dd>{tone}</dd></div>
                <div className="flex justify-between"><dt className="text-neutral-500">Style Pack</dt><dd className="capitalize">{stylePack}</dd></div>
                <div className="flex justify-between"><dt className="text-neutral-500">Mark Mode</dt><dd className="capitalize">{markMode}</dd></div>
                <div className="flex justify-between"><dt className="text-neutral-500">Output</dt><dd>{logoMode==="textIcon_svg" ? "Text + Icon (SVG)" : "Image + Text (PNG)"}</dd></div>
              </dl>
            </div>
          </div>

          {/* Logos header with Generate */}
          <div id="logos-section" className="flex items-center justify-between mt-2">
            <h2 className="text-lg font-semibold">Logos</h2>
            <button
              onClick={generate}
              className="px-4 py-2 rounded-lg bg-neutral-900 text-white hover:bg-black"
              title="Generate Logos"
            >
              Generate Logos
            </button>
          </div>

          {/* Logos grid */}
          {logos.length === 0 ? (
            <div className="text-sm text-neutral-500 border rounded-xl p-6 bg-white">
              No logos yet. Click <strong>Generate Logos</strong> to create previews.
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {logos.map((logo) => (
                <LogoCard
                  key={logo.id}
                  title={logo.filename}
                  source={logo.svg ?? logo.url ?? ""}
                  onPrimary={() => console.log("Set primary", logo.id)}
                  onFavorite={() => console.log("Favorite", logo.id)}
                  onDownload={async () => {
                    if (logo.kind === "svg" && logo.svg) {
                      const blob = new Blob([logo.svg], { type: "image/svg+xml;charset=utf-8" });
                      const a = document.createElement("a");
                      a.href = URL.createObjectURL(blob);
                      a.download = logo.filename || "logo.svg";
                      a.click();
                      URL.revokeObjectURL(a.href);
                    } else if (logo.kind === "png" && logo.url) {
                      const res = await fetch(logo.url);
                      const blob = await res.blob();
                      const a = document.createElement("a");
                      a.href = URL.createObjectURL(blob);
                      a.download = logo.filename || "logo.png";
                      a.click();
                      URL.revokeObjectURL(a.href);
                    }
                  }}
                />
              ))}
            </div>
          )}
        </section>
      )}

      {/* Bottom action bar */}
      <div className="mt-8 pt-4 border-t">
        <div className="flex items-center justify-end gap-2">
          <button
            className={`px-4 py-2 rounded-lg ${logos.length ? "bg-orange-500 hover:bg-orange-600 text-white" : "bg-neutral-200 text-neutral-500 cursor-not-allowed"}`}
            disabled={!logos.length}
            onClick={() => downloadAllAssets(logos)}
            title="Download Assets"
          >
            Download Assets
          </button>
        </div>
      </div>
    </div>
  );
}
