import React, { useEffect, useMemo, useState } from "react";
import { Heart, HeartOff, Sparkles, Search, Download, Copy, Palette, Layers, Wand2 } from "lucide-react";
import { applySvgColor } from "../../../utils/svg";
import { loadFavorites, saveFavorites, toggleFavorite, isFavorite } from "../../../store/favorites";

/**
 * ICONS — MVP NOTES
 * - Two modes: Browse (DB) and Generate (AI).
 * - Styles: modern, classic, flat, outlined, solid, hand-drawn, isometric (3D), material.
 * - All SVG so colors are easy to change in PPT/Keynote/Slides.
 * - Users can save "Favorites" (local) — later we can bind to Firestore.
 *
 * TODO (server/back-end integration):
 * - /api/icons/search?query=&style=&page= to query your icon DB (or a provider).
 * - /api/icons/generate { prompt, style } -> returns SVG string.
 * - Auth-bound cloud favorites if desired.
 */

// --- Style taxonomy ---
const STYLES = [
  { key: "modern", label: "Modern" },
  { key: "classic", label: "Classic" },
  { key: "flat", label: "Flat" },
  { key: "outlined", label: "Outlined" },
  { key: "solid", label: "Solid (Filled)" },
  { key: "handdrawn", label: "Hand-Drawn" },
  { key: "isometric", label: "3D/Isometric" },
  { key: "material", label: "Material Design" },
] as const;

type StyleKey = typeof STYLES[number]["key"];

// --- Mock DB: replace with your real icon provider results ---
type IconRecord = {
  id: string;
  name: string;
  style: StyleKey;
  // minimal SVG; replace with payloads from your provider
  svg: string;
  tags: string[];
};

// 12 demo icons across styles; swap in real source later
const MOCK_ICONS: IconRecord[] = [
  {
    id: "modern-rocket",
    name: "Rocket",
    style: "modern",
    tags: ["startup", "launch"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4.1c1.14-.07 2.28.28 3.16 1.16c.88.88 1.23 2.02 1.16 3.16l-3.74 3.74-4.1-4.1L14 4.1Z"/><path d="M5 19l3-3m-1 4l2-2"/><path d="m8.28 13.72l2 2"/><circle cx="15" cy="9" r="1"/></g></svg>`,
  },
  {
    id: "classic-lightbulb",
    name: "Lightbulb",
    style: "classic",
    tags: ["idea", "innovation"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18h6m-5 3h4"/><path d="M6 10a6 6 0 1 1 12 0c0 2.1-1.2 3.9-3 5v1H9v-1c-1.8-1.1-3-2.9-3-5Z"/></g></svg>`,
  },
  {
    id: "flat-chart",
    name: "Bar Chart",
    style: "flat",
    tags: ["data", "analytics"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="currentColor"><rect x="3" y="10" width="3" height="10" rx="1"/><rect x="9" y="6" width="3" height="14" rx="1"/><rect x="15" y="3" width="3" height="17" rx="1"/></g></svg>`,
  },
  {
    id: "outlined-user",
    name: "User",
    style: "outlined",
    tags: ["profile", "person"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-3.314 3.582-6 8-6s8 2.686 8 6"/></g></svg>`,
  },
  {
    id: "solid-shield",
    name: "Shield",
    style: "solid",
    tags: ["security", "protect"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M12 3l7 3v6c0 5-3.5 8.5-7 9c-3.5-.5-7-4-7-9V6l7-3Z"/></svg>`,
  },
  {
    id: "handdrawn-heart",
    name: "Heart",
    style: "handdrawn",
    tags: ["love", "like"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 20s-6-3.33-8.5-6.5C1 10.5 3 6 6.5 6C9 6 10.5 8 12 9.5C13.5 8 15 6 17.5 6C21 6 23 10.5 20.5 13.5C18 16.67 12 20 12 20Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
  },
  {
    id: "iso-cube",
    name: "Isometric Cube",
    style: "isometric",
    tags: ["3D", "box"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2l8 4v12l-8 4l-8-4V6z"/><path d="M20 6l-8 4l-8-4"/></g></svg>`,
  },
  {
    id: "material-home",
    name: "Home",
    style: "material",
    tags: ["house", "dashboard"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 3l9 8h-3v9h-12v-9H3l9-8z" fill="currentColor"/></svg>`,
  },
  {
    id: "outlined-link",
    name: "Link",
    style: "outlined",
    tags: ["url", "chain"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 14a5 5 0 0 1 0-7l1-1a5 5 0 0 1 7 7l-1 1"/><path d="M14 10a5 5 0 0 1 0 7l-1 1a5 5 0 1 1-7-7l1-1"/></g></svg>`,
  },
  {
    id: "solid-download",
    name: "Download",
    style: "solid",
    tags: ["arrow", "save"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M12 3a1 1 0 0 1 1 1v8.586l2.293-2.293a1 1 0 1 1 1.414 1.414l-4.007 4.007a1 1 0 0 1-1.4 0l-4.014-4.014a1 1 0 1 1 1.414-1.414L11 12.586V4a1 1 0 0 1 1-1Zm-7 15a1 1 0 0 1 1-1h12a1 1 0 1 1 0 2H6a1 1 0 0 1-1-1Z"/></svg>`,
  },
  {
    id: "flat-star",
    name: "Star",
    style: "flat",
    tags: ["favorite", "rating"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="m12 2l3.09 6.26L22 9.27l-5 4.87l1.18 6.88L12 17.77l-6.18 3.25L7 14.14l-5-4.87l6.91-1.01z"/></svg>`,
  },
  {
    id: "modern-folder",
    name: "Folder",
    style: "modern",
    tags: ["files", "assets"],
    svg: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="2"/></svg>`,
  },
];

// --- Helpers: download + clipboard
function downloadTextFile(filename: string, content: string) {
  const blob = new Blob([content], { type: "image/svg+xml;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}

async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

type Mode = "browse" | "generate";

export default function IconsPage() {
  const [mode, setMode] = useState<Mode>("browse");
  const [query, setQuery] = useState("");
  const [style, setStyle] = useState<StyleKey | "">("");
  const [color, setColor] = useState<string>("#0ea5e9"); // default accent for preview
  const [favorites, setFavorites] = useState<string[]>([]);

  const [genPrompt, setGenPrompt] = useState("");
  const [genStyle, setGenStyle] = useState<StyleKey>("outlined");
  const [genSvg, setGenSvg] = useState<string | null>(null);
  const [genBusy, setGenBusy] = useState(false);
  const [genError, setGenError] = useState<string | null>(null);

  useEffect(() => {
    setFavorites(loadFavorites());
  }, []);

  const data = useMemo(() => {
    const q = query.trim().toLowerCase();
    return MOCK_ICONS.filter((i) => {
      if (style && i.style !== style) return false;
      if (!q) return true;
      return i.name.toLowerCase().includes(q) || i.tags.some((t) => t.includes(q));
    });
  }, [query, style]);

  function handleToggleFavorite(id: string) {
    const updated = toggleFavorite(id);
    setFavorites(updated);
  }

  function renderStyleChips(current: string | "", onPick: (k: StyleKey | "") => void, compact = false) {
    return (
      <div className={`flex flex-wrap gap-2 ${compact ? "" : "mt-3"}`}>
        <button
          className={`px-3 py-1.5 rounded-full text-sm border ${current === "" ? "bg-white/10 text-white border-white/20" : "border-white/10 text-slate-300 hover:bg-white/5"}`}
          onClick={() => onPick("")}
        >
          All
        </button>
        {STYLES.map((s) => (
          <button
            key={s.key}
            className={`px-3 py-1.5 rounded-full text-sm border ${current === s.key ? "bg-white/10 text-white border-white/20" : "border-white/10 text-slate-300 hover:bg-white/5"}`}
            onClick={() => onPick(s.key)}
          >
            {s.label}
          </button>
        ))}
      </div>
    );
  }

  async function generateIcon() {
    setGenBusy(true);
    setGenError(null);
    setGenSvg(null);

    try {
      // ==== STUB: Call your backend route here ====
      // const res = await fetch("/api/icons/generate", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ prompt: genPrompt, style: genStyle })});
      // const json = await res.json(); // { svg: "<svg ...>...</svg>" }
      // setGenSvg(json.svg);

      // For now, mock a simple variant based on style
      const base = `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">${genStyle === "solid"
          ? `<circle cx="12" cy="12" r="8" fill="currentColor"/>`
          : `<circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2"/>`
        }</svg>`;
      setTimeout(() => {
        setGenSvg(base);
        setGenBusy(false);
      }, 600);
    } catch (e: any) {
      setGenBusy(false);
      setGenError("Generation failed. Try again.");
    }
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">Icons</h1>

        <div className="inline-flex rounded-xl overflow-hidden border border-white/10">
          <button
            className={`px-4 py-2 text-sm ${mode === "browse" ? "bg-white/10 text-white" : "text-slate-300 hover:bg-white/5"}`}
            onClick={() => setMode("browse")}
          >
            <Layers className="inline-block w-4 h-4 mr-2" />
            Browse
          </button>
          <button
            className={`px-4 py-2 text-sm ${mode === "generate" ? "bg-white/10 text-white" : "text-slate-300 hover:bg-white/5"}`}
            onClick={() => setMode("generate")}
          >
            <Wand2 className="inline-block w-4 h-4 mr-2" />
            Generate
          </button>
        </div>
      </div>

      {mode === "browse" ? (
        <>
          {/* Search + style row */}
          <div className="flex flex-wrap items-center gap-3">
            <div className="flex items-center gap-2 flex-1 min-w-[260px]">
              <div className="relative flex-1">
                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input
                  className="w-full pl-9 pr-3 py-2 rounded-lg bg-slate-900/60 border border-white/10 text-slate-100 placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-sky-500/50"
                  placeholder="Search icons (e.g., rocket, chart, heart)…"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                />
              </div>
              <label className="flex items-center gap-2 text-sm text-slate-300 px-3 py-2 bg-slate-900/60 rounded-lg border border-white/10">
                <Palette className="w-4 h-4" />
                <input
                  type="color"
                  className="h-6 w-6 bg-transparent cursor-pointer"
                  value={color}
                  onChange={(e) => setColor(e.target.value)}
                  title="Preview color"
                />
              </label>
            </div>
          </div>

          {renderStyleChips(style, (k) => setStyle(k))}

          {/* Grid */}
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6 gap-4 mt-4">
            {data.map((icon) => {
              const colored = applySvgColor(icon.svg, color);
              const fav = isFavorite(favorites, icon.id);

              return (
                <div key={icon.id} className="group relative rounded-xl border border-white/10 bg-slate-900/60 p-3">
                  <div className="aspect-square flex items-center justify-center rounded-lg bg-slate-950/60">
                    <div
                      className="w-16 h-16 md:w-20 md:h-20"
                      dangerouslySetInnerHTML={{ __html: colored }}
                      aria-label={icon.name}
                    />
                  </div>

                  <div className="mt-3 flex items-center justify-between">
                    <div>
                      <div className="text-sm font-medium text-white">{icon.name}</div>
                      <div className="text-xs text-slate-400">{STYLES.find((s) => s.key === icon.style)?.label}</div>
                    </div>

                    <button
                      className={`p-2 rounded-lg border ${fav ? "border-pink-500/40 text-pink-400 bg-pink-500/10" : "border-white/10 text-slate-300 hover:bg-white/5"}`}
                      onClick={() => handleToggleFavorite(icon.id)}
                      title={fav ? "Remove favorite" : "Save to favorites"}
                    >
                      {fav ? <Heart className="w-4 h-4" /> : <HeartOff className="w-4 h-4" />}
                    </button>
                  </div>

                  {/* Actions */}
                  <div className="mt-2 grid grid-cols-2 gap-2">
                    <button
                      className="inline-flex items-center justify-center gap-2 px-3 py-2 text-sm rounded-lg border border-white/10 hover:bg-white/5"
                      onClick={() => copyToClipboard(applySvgColor(icon.svg, color))}
                    >
                      <Copy className="w-4 h-4" /> Copy SVG
                    </button>
                    <button
                      className="inline-flex items-center justify-center gap-2 px-3 py-2 text-sm rounded-lg border border-white/10 hover:bg-white/5"
                      onClick={() => downloadTextFile(`${icon.name}.svg`, applySvgColor(icon.svg, color))}
                    >
                      <Download className="w-4 h-4" /> Download
                    </button>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Favorites strip */}
          <div className="mt-8">
            <h2 className="text-lg font-semibold mb-3">Favorites</h2>
            {favorites.length === 0 ? (
              <p className="text-slate-400">No favorites yet. Tap the heart on any icon to save it here.</p>
            ) : (
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 xl:grid-cols-8 gap-3">
                {favorites.map((id) => {
                  const icon = MOCK_ICONS.find((i) => i.id === id);
                  if (!icon) return null;
                  const colored = applySvgColor(icon.svg, color);
                  return (
                    <div key={id} className="rounded-xl border border-white/10 bg-slate-900/60 p-3">
                      <div className="aspect-square flex items-center justify-center rounded-lg bg-slate-950/60">
                        <div className="w-12 h-12" dangerouslySetInnerHTML={{ __html: colored }} />
                      </div>
                      <div className="mt-2 text-xs text-slate-300 truncate">{icon.name}</div>
                      <div className="mt-2 grid grid-cols-2 gap-2">
                        <button
                          className="inline-flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded border border-white/10 hover:bg-white/5"
                          onClick={() => copyToClipboard(applySvgColor(icon.svg, color))}
                        >
                          <Copy className="w-3.5 h-3.5" /> Copy
                        </button>
                        <button
                          className="inline-flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded border border-white/10 hover:bg-white/5"
                          onClick={() => downloadTextFile(`${icon.name}.svg`, applySvgColor(icon.svg, color))}
                        >
                          <Download className="w-3.5 h-3.5" /> SVG
                        </button>
                      </div>
                      <button
                        className="mt-2 w-full inline-flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded border border-pink-500/30 text-pink-300 hover:bg-pink-500/10"
                        onClick={() => handleToggleFavorite(id)}
                      >
                        <Heart className="w-3.5 h-3.5" /> Remove
                      </button>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </>
      ) : (
        // === Generate Mode ===
        <div className="grid md:grid-cols-2 gap-6">
          <div className="rounded-2xl border border-white/10 bg-slate-900/60 p-5">
            <h2 className="text-lg font-semibold">Generate a Unique Icon</h2>
            <p className="text-slate-400 text-sm mt-1">
              Describe the icon you need. Output will be pure SVG so you can recolor it easily in PPT/Keynote/Slides.
            </p>

            <label className="block mt-4 text-sm text-slate-300">Prompt</label>
            <textarea
              className="mt-1 w-full min-h-[120px] rounded-lg bg-slate-950/60 border border-white/10 p-3 text-slate-100 placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-sky-500/50"
              placeholder="e.g., 'A flat rocket icon pointing upward with a small window, minimal detail'"
              value={genPrompt}
              onChange={(e) => setGenPrompt(e.target.value)}
            />

            <label className="block mt-4 text-sm text-slate-300">Style</label>
            {renderStyleChips(genStyle, (k) => setGenStyle((k || "outlined") as StyleKey), true)}

            <div className="mt-4 flex items-center gap-3">
              <label className="flex items-center gap-2 text-sm text-slate-300 px-3 py-2 bg-slate-900/60 rounded-lg border border-white/10">
                <Palette className="w-4 h-4" />
                <input
                  type="color"
                  className="h-6 w-6 bg-transparent cursor-pointer"
                  value={color}
                  onChange={(e) => setColor(e.target.value)}
                  title="Preview color"
                />
              </label>

              <button
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-sky-600 hover:bg-sky-700 text-white disabled:opacity-60"
                onClick={generateIcon}
                disabled={genBusy || !genPrompt.trim()}
              >
                <Sparkles className="w-4 h-4" />
                {genBusy ? "Generating…" : "Generate SVG"}
              </button>
            </div>

            {genError && <p className="mt-3 text-sm text-rose-400">{genError}</p>}
          </div>

          <div className="rounded-2xl border border-white/10 bg-slate-900/60 p-5">
            <h2 className="text-lg font-semibold">Preview & Export</h2>
            <div className="mt-4 aspect-square rounded-xl border border-white/10 bg-slate-950/60 flex items-center justify-center">
              {genSvg ? (
                <div
                  className="w-24 h-24"
                  dangerouslySetInnerHTML={{ __html: applySvgColor(genSvg, color) }}
                />
              ) : (
                <div className="text-slate-500 text-sm">No icon generated yet.</div>
              )}
            </div>

            <div className="mt-4 grid grid-cols-2 gap-3">
              <button
                className="inline-flex items-center justify-center gap-2 px-3 py-2 text-sm rounded-lg border border-white/10 hover:bg-white/5 disabled:opacity-50"
                onClick={() => genSvg && copyToClipboard(applySvgColor(genSvg, color))}
                disabled={!genSvg}
              >
                <Copy className="w-4 h-4" /> Copy SVG
              </button>
              <button
                className="inline-flex items-center justify-center gap-2 px-3 py-2 text-sm rounded-lg border border-white/10 hover:bg-white/5 disabled:opacity-50"
                onClick={() => genSvg && downloadTextFile(`generated-icon.svg`, applySvgColor(genSvg, color))}
                disabled={!genSvg}
              >
                <Download className="w-4 h-4" /> Download SVG
              </button>
            </div>

            <p className="mt-3 text-xs text-slate-400">
              Tip: Paste SVGs directly into PowerPoint (Insert &rarr; Pictures &rarr; This Device) or drag in — then change
              fill/stroke colors natively.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
