import React, { useMemo, useState } from "react";
import { useBrandKit } from "../../../utils/brand";
import { useLocalStorage } from "../../../hooks/useLocalStorage";

// --- Types ---
type Size = "16x9" | "4x3";
type LayoutType = "hubSpoke" | "stepsHorizontal" | "mindmap" | "circularList";

type LibraryItem = {
  id: string;
  name: string;
  layout: LayoutType;
  count: number;
  defaultLabels: string[];
  defaultNotes?: string[];
  colorAIdx?: number; // index into brand accents (primary)
  colorBIdx?: number; // index into brand accents (secondary)
};

// --- Demo library (expand anytime) ---
const LIBRARY: LibraryItem[] = [
  {
    id: "hub6",
    name: "Hub & Spoke (6)",
    layout: "hubSpoke",
    count: 6,
    defaultLabels: ["What","Why","Who","Where","When","How"],
    defaultNotes: ["","Optional","","","",""]
  },
  {
    id: "steps6",
    name: "Steps (6)",
    layout: "stepsHorizontal",
    count: 6,
    defaultLabels: ["Discover","Define","Design","Develop","Deploy","Debrief"],
  },
  {
    id: "mind6",
    name: "Mindmap (6)",
    layout: "mindmap",
    count: 6,
    defaultLabels: ["Strategy","People","Process","Tech","Brand","Finance"],
  },
  {
    id: "circle6",
    name: "Radial Timeline (6)",
    layout: "circularList",
    count: 6,
    defaultLabels: ["Q1","Q2","Q3","Q4","Q5","Q6"],
  },
];

// --- Simple SVG previews for each layout (schematic) ---
function Preview({ layout, count=6, colorA="#0EA5E9", colorB="#64748B" }: {layout: LayoutType; count?: number; colorA?: string; colorB?: string;}) {
  const size = 200;
  const cx = size/2, cy = size/2;
  const R = size*0.32;
  const dot = 12;

  if (layout === "hubSpoke") {
    const pts = Array.from({length: count}, (_,i)=> {
      const a = (Math.PI*2*i)/count - Math.PI/2;
      return { x: cx + R*Math.cos(a), y: cy + R*Math.sin(a) };
    });
    return (
      <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
        <circle cx={cx} cy={cy} r={R*0.6} fill="#0F172A" stroke="#fff" strokeWidth="1"/>
        {pts.map((p,i)=>(
          <g key={i}>
            <line x1={cx} y1={cy} x2={p.x} y2={p.y} stroke="#CBD5E1" strokeWidth="1.5"/>
            <circle cx={p.x} cy={p.y} r={dot/2} fill={i%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
          </g>
        ))}
      </svg>
    );
  }

  if (layout === "stepsHorizontal") {
    const margin=16, gap=6;
    const boxW=(size - margin*2 - gap*(count-1))/count, boxH=38, y= size*0.45;
    return (
      <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
        {Array.from({length: count}, (_,i)=>{
          const x = margin + i*(boxW+gap);
          return (
            <g key={i}>
              <rect x={x} y={y} width={boxW} height={boxH} rx="8" fill={i%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
              <text x={x+8} y={y+14} fontSize="10" fill="#fff" fontWeight="700">{String(i+1).padStart(2,"0")}</text>
            </g>
          );
        })}
        <line x1={margin} y1={y+boxH+6} x2={size-margin} y2={y+boxH+6} stroke="#CBD5E1" strokeWidth="1"/>
      </svg>
    );
  }

  if (layout === "mindmap") {
    const perSide = Math.ceil(count/2);
    const leftX = 20, rightX = size-80;
    const topY = 30, stepY = (size-60)/(perSide-1 || 1);
    return (
      <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
        <ellipse cx={cx} cy={cy} rx={34} ry={24} fill="#0F172A" stroke="#fff" strokeWidth="1"/>
        {/* left */}
        {Array.from({length: perSide}, (_,j)=>{
          const y = topY + j*stepY;
          return (
            <g key={`L${j}`}>
              <line x1={cx-10} y1={cy} x2={leftX+60} y2={y+16} stroke="#94A3B8" strokeWidth="1.2"/>
              <rect x={leftX} y={y} width={60} height={24} rx="6" fill={j%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
            </g>
          );
        })}
        {/* right */}
        {Array.from({length: perSide}, (_,j)=>{
          const y = topY + j*stepY;
          return (
            <g key={`R${j}`}>
              <line x1={cx+10} y1={cy} x2={rightX} y2={y+16} stroke="#94A3B8" strokeWidth="1.2"/>
              <rect x={rightX} y={y} width={60} height={24} rx="6" fill={j%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
            </g>
          );
        })}
      </svg>
    );
  }

  // circularList
  const pts = Array.from({length: count}, (_,i)=> {
    const a = (Math.PI*2*i)/count - Math.PI/2;
    return { x: cx + R*Math.cos(a), y: cy + R*Math.sin(a) };
  });
  return (
    <svg width="100%" viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={R} fill="none" stroke="#CBD5E1" strokeWidth="1.2"/>
      {pts.map((p,i)=>(
        <circle key={i} cx={p.x} cy={p.y} r={dot/2} fill={i%2?colorB:colorA} stroke="#fff" strokeWidth="1"/>
      ))}
    </svg>
  );
}

export default function InfographicsLibrary() {
  const brand = useBrandKit();
  const [size, setSize] = useLocalStorage<Size>("ig.size","16x9");
  // selection + per-card color overrides
  const [selected, setSelected] = useState<Record<string, boolean>>({});
  const [overrides, setOverrides] = useState<Record<string, {a: string; b: string}>>({});

  const accents = [
    brand.colors.primary || "#0EA5E9",
    brand.colors.accent  || "#F59E0B",
    brand.colors.neutral || "#64748B",
    "#8B5CF6", "#22C55E", "#EF4444"
  ];

  function toggle(id: string) {
    setSelected(s => ({...s, [id]: !s[id]}));
  }

  function setColor(id: string, key: "a"|"b", value: string) {
    setOverrides(o => ({...o, [id]: {...(o[id] || {a: accents[0], b: accents[2]}), [key]: value}}));
  }

  async function quickDownload(item: LibraryItem) {
    const colors = [
      overrides[item.id]?.a || accents[item.colorAIdx ?? 0] || accents[0],
      overrides[item.id]?.b || accents[item.colorBIdx ?? 2] || accents[2]
    ];
    const payload = {
      size,
      layout: item.layout,
      count: item.count,
      centerTitle: (item.layout === "hubSpoke" || item.layout === "mindmap") ? "Topic" : undefined,
      labels: item.defaultLabels,
      notes: item.defaultNotes || [],
      colors, // use 2-colors: server cycles as needed
      brand: { fonts: { heading: brand.fonts?.heading || "Inter", body: brand.fonts?.body || "Inter" }, accents },
      iconsSvg: Array.from({length: item.count}, ()=>null),
      assets: { logoDataUrl: null, logoPlacement: "none", logoScale: 1 }
    };
    const res = await fetch("/api/infographics/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
    if (!res.ok) { alert("Generate failed"); return; }
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `${item.name}.pptx`; a.click();
    URL.revokeObjectURL(url);
  }

  function addSelectedToTemplate() {
    // Flatten selected cards into pt.infographicsDetailed
    const key = "pt.infographicsDetailed";
    const prev = JSON.parse(localStorage.getItem(key) || "[]");

    const picks = LIBRARY.filter(i => selected[i.id]).map(i => {
      const colors = [
        overrides[i.id]?.a || accents[i.colorAIdx ?? 0] || accents[0],
        overrides[i.id]?.b || accents[i.colorBIdx ?? 2] || accents[2]
      ];
      return {
        layout: i.layout,
        count: i.count,
        centerTitle: (i.layout === "hubSpoke" || i.layout === "mindmap") ? "Topic" : undefined,
        labels: i.defaultLabels,
        notes: i.defaultNotes || [],
        // The template builder’s detailed renderer uses brand accents; include colors as hint
        colorsHint: colors,
      };
    });

    localStorage.setItem(key, JSON.stringify([...prev, ...picks]));
    alert(`${picks.length} page(s) added to your Presentation Template.`);
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Infographics Library</h1>
        <div className="flex items-center gap-2">
          <div className="hidden sm: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>
          <button onClick={addSelectedToTemplate} className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white">
            Add Selected to Template
          </button>
        </div>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {LIBRARY.map(item => {
          const sel = !!selected[item.id];
          const colA = overrides[item.id]?.a || accents[item.colorAIdx ?? 0] || accents[0];
          const colB = overrides[item.id]?.b || accents[item.colorBIdx ?? 2] || accents[2];
          return (
            <div key={item.id} className={`rounded-xl border ${sel ? "border-sky-500/50 bg-sky-500/5" : "border-white/10 bg-slate-900/60"} p-4`}>
              <div className="flex items-start justify-between">
                <div>
                  <div className="font-medium">{item.name}</div>
                  <div className="text-xs text-slate-400">{item.count} sections</div>
                </div>
                <label className="inline-flex items-center gap-2 text-sm">
                  <input type="checkbox" checked={sel} onChange={()=>toggle(item.id)} className="accent-sky-500"/>
                  Select
                </label>
              </div>

              <div className="mt-3 rounded-lg overflow-hidden border border-white/10 bg-white">
                <div className="aspect-video">
                  <Preview layout={item.layout} count={item.count} colorA={colA} colorB={colB}/>
                </div>
              </div>

              <div className="mt-3 grid grid-cols-2 gap-2">
                <label className="flex items-center gap-2 text-xs">
                  <input type="color" value={colA} onChange={(e)=>setColor(item.id,"a", e.target.value)} />
                  <span>Primary</span>
                </label>
                <label className="flex items-center gap-2 text-xs">
                  <input type="color" value={colB} onChange={(e)=>setColor(item.id,"b", e.target.value)} />
                  <span>Secondary</span>
                </label>
              </div>

              <div className="mt-3 flex items-center justify-between">
                <button onClick={()=>quickDownload(item)} className="px-3 py-1.5 rounded-lg border border-white/10 hover:bg-white/5 text-sm">
                  Quick Download
                </button>
                <span className="text-xs text-slate-400">Editable in PPT</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
