import React, { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import { Download, Eye, Info, Star, Filter, RefreshCcw, Search, Link as LinkIcon } from "lucide-react";
// shadcn/ui
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

// IBrandBiz palette helpers
const IBB = {
  green: "#00CB51",
  orange: "#FF8B00",
  darkGreen: "#30342d",
  darkGray: "#231f20",
  blue: "#274b9b",
  olive: "#978752",
  lightGreen: "#6dc282",
  white: "#ffffff",
};

// Types
export type StoragePaths = {
  docx?: string;
  preview?: string;
  thumb?: string;
};

export type TemplateDoc = {
  title: string;
  slug: string;
  category: string;
  industries?: string[];
  isMaster?: boolean;
  currentVersion?: string;
  storagePaths?: StoragePaths;
  updatedAt?: number | string | null;
};

const API_BASE = "/api/bp-templates-firebase"; // public routes mounted at base

function classNames(...cls: (string | false | undefined)[]) {
  return cls.filter(Boolean).join(" ");
}

export default function BusinessPlanTemplatesPage() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [items, setItems] = useState<TemplateDoc[]>([]);
  const [q, setQ] = useState("");
  const [category, setCategory] = useState<string>("All");
  const [onlyMaster, setOnlyMaster] = useState<boolean>(false);

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        setLoading(true);
        const res = await fetch(`${API_BASE}/list`, { cache: "no-store" });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data: TemplateDoc[] = await res.json();
        if (alive) setItems(data);
      } catch (e: any) {
        setError(e?.message || "Failed to load templates");
      } finally {
        setLoading(false);
      }
    })();
    return () => {
      alive = false;
    };
  }, []);

  const categories = useMemo(() => {
    const set = new Set<string>(["All"]);
    items.forEach((t) => set.add(t.category || "General"));
    return Array.from(set);
  }, [items]);

  const filtered = useMemo(() => {
    const needle = q.trim().toLowerCase();
    return items.filter((t) => {
      if (onlyMaster && !t.isMaster) return false;
      if (category !== "All" && t.category !== category) return false;
      if (!needle) return true;
      const hay = [
        t.title,
        t.slug,
        t.category,
        ...(t.industries || []),
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return hay.includes(needle);
    });
  }, [items, q, category, onlyMaster]);

  const onDownload = (slug: string) => {
    // Redirect to server which returns signed or public URL
    window.open(`${API_BASE}/${encodeURIComponent(slug)}/download`, "_blank");
  };

  const onPreview = (t: TemplateDoc) => {
    const url = t.storagePaths?.preview || t.storagePaths?.thumb;
    if (url) window.open(url, "_blank");
  };

  return (
    <div className="min-h-screen bg-[#f8fafb]">
      {/* Hero */}
      <div
        className="relative overflow-hidden"
        style={{ background: `linear-gradient(135deg, ${IBB.blue} 0%, ${IBB.green} 100%)` }}
      >
        <div className="mx-auto max-w-7xl px-6 py-10 text-white">
          <motion.h1
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-3xl md:text-4xl font-bold tracking-tight"
          >
            Business Plan Templates
          </motion.h1>
          <p className="mt-2 text-white/90">
            Free, lender-ready templates. One-click download. Upsell to AI Builder when ready.
          </p>
          <div className="mt-6 grid grid-cols-1 gap-3 md:grid-cols-12">
            <div className="md:col-span-7">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-white/80" />
                <Input
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  placeholder="Search by title, category, or tags…"
                  className="pl-9 bg-white/10 border-white/20 text-white placeholder:text-white/70 focus-visible:ring-white"
                />
              </div>
            </div>
            <div className="md:col-span-3">
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="w-full h-10 rounded-xl bg-white/10 border border-white/20 text-white px-3"
              >
                {categories.map((c) => (
                  <option key={c} value={c} className="text-black">
                    {c}
                  </option>
                ))}
              </select>
            </div>
            <div className="md:col-span-2 flex items-center gap-2">
              <Button
                variant="secondary"
                onClick={() => setOnlyMaster((s) => !s)}
                className={classNames(
                  "w-full rounded-xl",
                  onlyMaster ? "bg-white text-black" : "bg-white/10 text-white"
                )}
              >
                <Filter className="mr-2 h-4 w-4" /> {onlyMaster ? "Master only" : "All versions"}
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="mx-auto max-w-7xl px-6 py-10">
        {/* Status row */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <span className="inline-flex items-center gap-1"><RefreshCcw className="h-4 w-4"/> Live</span>
            <span>•</span>
            <span>{filtered.length} result{filtered.length === 1 ? "" : "s"}</span>
          </div>
          <a
            href="/ai/builder"
            className="text-sm font-medium text-[var(--ibb-green,#00CB51)] hover:underline"
          >
            Try the AI Business Plan Builder →
          </a>
        </div>

        {/* Grid */}
        {loading ? (
          <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <Card key={i} className="overflow-hidden rounded-2xl shadow-sm">
                <div className="h-40 w-full animate-pulse bg-gray-200" />
                <CardHeader className="space-y-2">
                  <div className="h-5 w-2/3 animate-pulse bg-gray-200 rounded" />
                  <div className="h-4 w-1/3 animate-pulse bg-gray-200 rounded" />
                </CardHeader>
                <CardContent>
                  <div className="flex gap-2">
                    <div className="h-6 w-20 animate-pulse bg-gray-200 rounded-full" />
                    <div className="h-6 w-24 animate-pulse bg-gray-200 rounded-full" />
                  </div>
                </CardContent>
                <CardFooter className="flex gap-2">
                  <div className="h-9 w-24 animate-pulse bg-gray-200 rounded-xl" />
                  <div className="h-9 w-24 animate-pulse bg-gray-200 rounded-xl" />
                </CardFooter>
              </Card>
            ))}
          </div>
        ) : error ? (
          <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-red-800">
            {error}
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-gray-600">No templates match your search.</div>
        ) : (
          <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {filtered.map((t) => (
              <Card key={t.slug} className="overflow-hidden rounded-2xl shadow-sm">
                <div className="relative">
                  {t.storagePaths?.thumb || t.storagePaths?.preview ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={t.storagePaths?.thumb || t.storagePaths?.preview}
                      alt={`${t.title} thumbnail`}
                      className="h-44 w-full object-cover"
                      loading="lazy"
                    />
                  ) : (
                    <div
                      className="h-44 w-full"
                      style={{
                        background: `linear-gradient(135deg, ${IBB.darkGray} 0%, ${IBB.darkGreen} 100%)`,
                      }}
                    />
                  )}
                  {t.isMaster && (
                    <span className="absolute top-3 left-3 inline-flex items-center gap-1 rounded-full bg-black/70 px-2 py-1 text-xs font-medium text-white">
                      <Star className="h-3.5 w-3.5 text-yellow-300" /> Master
                    </span>
                  )}
                </div>
                <CardHeader>
                  <h3 className="text-lg font-semibold text-gray-900">{t.title}</h3>
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge className="bg-[rgba(0,203,81,0.15)] text-[${IBB.green}] hover:bg-[rgba(0,203,81,0.25)]">
                      {t.category || "General"}
                    </Badge>
                    {(t.industries || []).slice(0, 2).map((tag) => (
                      <Badge key={tag} variant="secondary" className="bg-gray-100 text-gray-800">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-sm text-gray-600">
                    Version: <span className="font-medium">{t.currentVersion || "—"}</span>
                  </div>
                </CardContent>
                <CardFooter className="flex flex-wrap gap-2">
                  <Button
                    className="rounded-xl bg-[--ibb-green] hover:bg-emerald-600"
                    style={{
                      // CSS var fallback to palette
                      // @ts-ignore
                      "--ibb-green": IBB.green,
                    }}
                    onClick={() => onDownload(t.slug)}
                  >
                    <Download className="mr-2 h-4 w-4" /> Download
                  </Button>
                  <Button variant="secondary" className="rounded-xl" onClick={() => onPreview(t)}>
                    <Eye className="mr-2 h-4 w-4" /> Preview
                  </Button>
                  <a
                    href={`${API_BASE}/${encodeURIComponent(t.slug)}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    <Button variant="outline" className="rounded-xl">
                      <Info className="mr-2 h-4 w-4" /> Details
                    </Button>
                  </a>
                  <Button
                    variant="ghost"
                    className="ml-auto rounded-xl"
                    onClick={() => navigator.clipboard.writeText(`${window.location.origin}/api/bp-templates-firebase/${t.slug}/download`)}
                    title="Copy download link"
                  >
                    <LinkIcon className="mr-2 h-4 w-4" /> Copy link
                  </Button>
                </CardFooter>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
