"use client";

import { useEffect, useState, useCallback } from "react";
import { motion } from "framer-motion";
import {
  Tag, RefreshCw, Loader2, CheckCircle2, Clock, AlertCircle,
  ExternalLink, TrendingUp, Car, Star, Plus, X,
} from "lucide-react";
import { fetchBrandsList, generateBrandPage, createBrand } from "@/lib/api";
import type { BrandListItem } from "@/lib/types";
import { cn } from "@/lib/utils";

function StatCard({
  icon: Icon,
  label,
  value,
  color = "blue",
}: {
  icon: React.ElementType;
  label: string;
  value: number | string;
  color?: "blue" | "green" | "amber" | "purple";
}) {
  const g = {
    blue:   "from-blue-500 to-blue-600 shadow-blue-100",
    green:  "from-green-500 to-emerald-500 shadow-green-100",
    amber:  "from-amber-400 to-orange-500 shadow-amber-100",
    purple: "from-violet-500 to-purple-500 shadow-violet-100",
  };
  return (
    <div className="rounded-[24px] bg-white border border-gray-200/60 p-5 shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
      <div className={cn("w-10 h-10 rounded-2xl bg-gradient-to-br flex items-center justify-center mb-3 shadow-lg", g[color])}>
        <Icon className="w-5 h-5 text-white" />
      </div>
      <p className="text-2xl font-black text-gray-900">{value}</p>
      <p className="text-xs font-bold text-gray-500 mt-1">{label}</p>
    </div>
  );
}

function BrandRow({
  brand,
  onRegenerate,
}: {
  brand: BrandListItem;
  onRegenerate: (slug: string) => Promise<void>;
}) {
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleRegen() {
    setLoading(true);
    setError(null);
    try {
      await onRegenerate(brand.brandSlug);
      setDone(true);
      setTimeout(() => setDone(false), 3000);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex items-center gap-4 p-4 bg-white rounded-2xl border border-gray-100 hover:border-gray-200 transition-colors">
      {/* Brand initial */}
      <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-black text-sm flex-shrink-0">
        {brand.brand.charAt(0)}
      </div>

      {/* Brand info */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="font-bold text-gray-900 text-sm">{brand.brand}</span>
          {brand.hasPage ? (
            <span className="text-xs bg-green-50 text-green-700 font-semibold px-2 py-0.5 rounded-full border border-green-200 flex items-center gap-1">
              <CheckCircle2 className="w-3 h-3" /> SEO Ready
            </span>
          ) : (
            <span className="text-xs bg-amber-50 text-amber-700 font-semibold px-2 py-0.5 rounded-full border border-amber-200 flex items-center gap-1">
              <Clock className="w-3 h-3" /> No AI Page
            </span>
          )}
        </div>
        <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
          <span>{brand.totalCars} cars</span>
          {brand.priceFrom > 0 && (
            <span>₹{brand.priceFrom}–{brand.priceTo}L</span>
          )}
          {brand.avgRating > 0 && (
            <span className="flex items-center gap-0.5">
              <Star className="w-3 h-3 text-amber-400 fill-current" />
              {brand.avgRating.toFixed(1)}
            </span>
          )}
          {brand.pageUpdatedAt && (
            <span>Updated {new Date(brand.pageUpdatedAt).toLocaleDateString("en-IN")}</span>
          )}
        </div>
        {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 flex-shrink-0">
        <a
          href={`/brands/${brand.brandSlug}`}
          target="_blank"
          rel="noopener noreferrer"
          className="p-2 rounded-xl hover:bg-gray-100 text-gray-400 hover:text-blue-600 transition-colors"
          title="View brand page"
        >
          <ExternalLink className="w-4 h-4" />
        </a>
        <button
          onClick={handleRegen}
          disabled={loading}
          title="Regenerate AI content"
          className={cn(
            "flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold transition-all",
            done
              ? "bg-green-50 text-green-700 border border-green-200"
              : "bg-blue-50 text-blue-700 border border-blue-200 hover:bg-blue-100"
          )}
        >
          {loading ? (
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
          ) : done ? (
            <CheckCircle2 className="w-3.5 h-3.5" />
          ) : (
            <RefreshCw className="w-3.5 h-3.5" />
          )}
          {done ? "Done" : "Regenerate"}
        </button>
      </div>
    </div>
  );
}

function AddBrandModal({
  open,
  onClose,
  onCreated,
}: {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
}) {
  const [brandName, setBrandName] = useState("");
  const [country, setCountry] = useState("India");
  const [logoUrl, setLogoUrl] = useState("");
  const [carsCount, setCarsCount] = useState(5);
  const [loading, setLoading] = useState<"none" | "only" | "ai">("none");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  useEffect(() => {
    if (!open) {
      setBrandName("");
      setCountry("India");
      setLogoUrl("");
      setCarsCount(5);
      setLoading("none");
      setError(null);
      setSuccess(null);
    }
  }, [open]);

  if (!open) return null;

  async function handleSubmit(generateAiCars: boolean) {
    if (!brandName.trim()) {
      setError("Brand name is required.");
      return;
    }
    setLoading(generateAiCars ? "ai" : "only");
    setError(null);
    setSuccess(null);
    try {
      const result = await createBrand({
        brandName: brandName.trim(),
        country: country.trim() || "India",
        logoUrl: logoUrl.trim() || undefined,
        carsCount,
        generateAiCars,
      });
      setSuccess(result.message);
      onCreated();
      setTimeout(() => onClose(), 1500);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to create brand");
    } finally {
      setLoading("none");
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm mt-20">
      <motion.div
        initial={{ opacity: 0, scale: 0.96 }}
        animate={{ opacity: 1, scale: 1 }}
        className="w-full max-w-md bg-white rounded-3xl shadow-2xl border border-gray-100 overflow-hidden"
      >
        <div className="flex items-center justify-between px-6 py-2 border-b border-gray-100">
          <div>
            <h2 className="text-lg font-black text-gray-900">Add Brand</h2>
            <p className="text-xs text-gray-500 mt-0.5">Create a brand page with optional AI cars</p>
          </div>
          <button
            onClick={onClose}
            disabled={loading !== "none"}
            className="p-2 rounded-xl hover:bg-gray-100 text-gray-400 transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="px-6 py-5 space-y-4">
          <div>
            <label className="block text-xs font-bold text-gray-600 mb-1.5">Brand Name *</label>
            <input
              value={brandName}
              onChange={(e) => setBrandName(e.target.value)}
              placeholder="e.g. Citroën"
              disabled={loading !== "none"}
              className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-60"
            />
          </div>
          <div>
            <label className="block text-xs font-bold text-gray-600 mb-1.5">Country</label>
            <input
              value={country}
              onChange={(e) => setCountry(e.target.value)}
              placeholder="India"
              disabled={loading !== "none"}
              className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-60"
            />
          </div>
          <div>
            <label className="block text-xs font-bold text-gray-600 mb-1.5">Logo URL (optional)</label>
            <input
              value={logoUrl}
              onChange={(e) => setLogoUrl(e.target.value)}
              placeholder="https://..."
              disabled={loading !== "none"}
              className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-60"
            />
          </div>
          <div>
            <label className="block text-xs font-bold text-gray-600 mb-1.5">Generate Cars Count</label>
            <input
              type="number"
              min={1}
              max={20}
              value={carsCount}
              onChange={(e) => setCarsCount(Math.max(1, Math.min(20, Number(e.target.value) || 1)))}
              disabled={loading !== "none"}
              className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 disabled:opacity-60"
            />
            <p className="text-xs text-gray-400 mt-1">Used when creating brand with AI cars (1–20)</p>
          </div>

          {error && (
            <p className="text-xs text-red-600 bg-red-50 border border-red-100 rounded-xl px-3 py-2">{error}</p>
          )}
          {success && (
            <p className="text-xs text-green-700 bg-green-50 border border-green-100 rounded-xl px-3 py-2 flex items-center gap-1.5">
              <CheckCircle2 className="w-3.5 h-3.5" /> {success}
            </p>
          )}
        </div>

        <div className="px-6 py-2 border-t border-gray-100 flex flex-col sm:flex-row gap-2">
          <button
            onClick={() => handleSubmit(false)}
            disabled={loading !== "none"}
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 text-sm font-bold text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-60"
          >
            {loading === "only" ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
            Create Brand Only
          </button>
          <button
            onClick={() => handleSubmit(true)}
            disabled={loading !== "none"}
            className="flex-1 flex items-center justify-center gap-2 px-2 py-2.5 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-bold shadow-lg shadow-blue-100 hover:opacity-90 transition-opacity disabled:opacity-60"
          >
            {loading === "ai" ? <Loader2 className="w-4 h-4 animate-spin" /> : <TrendingUp className="w-4 h-4" />}
            Create Brand + AI Cars
          </button>
        </div>
      </motion.div>
    </div>
  );
}

export default function AdminBrandsPage() {
  const [brands, setBrands] = useState<BrandListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [regenAll, setRegenAll] = useState(false);
  const [filter, setFilter] = useState<"all" | "with-page" | "without-page">("all");
  const [addOpen, setAddOpen] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchBrandsList();
      setBrands(res.brands);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  async function handleRegenerate(slug: string) {
    await generateBrandPage(slug);
    await load();
  }

  async function handleRegenAll() {
    const missing = brands.filter((b) => !b.hasPage);
    if (!missing.length) return;
    setRegenAll(true);
    for (const b of missing) {
      try { await generateBrandPage(b.brandSlug); } catch { /* quota errors — skip */ }
    }
    await load();
    setRegenAll(false);
  }

  const filtered = brands.filter((b) => {
    const matchSearch = !search || b.brand.toLowerCase().includes(search.toLowerCase());
    const matchFilter =
      filter === "all" ? true :
      filter === "with-page" ? b.hasPage :
      !b.hasPage;
    return matchSearch && matchFilter;
  });

  const withPage    = brands.filter((b) => b.hasPage).length;
  const withoutPage = brands.filter((b) => !b.hasPage).length;
  const totalCars   = brands.reduce((s, b) => s + b.totalCars, 0);

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-5xl mx-auto">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-black text-gray-900">Brand Pages</h1>
          <p className="text-sm text-gray-500 mt-0.5">AI-generated landing pages for each car brand</p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => setAddOpen(true)}
            className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 text-white text-sm font-bold shadow-lg shadow-emerald-100 hover:opacity-90 transition-opacity"
          >
            <Plus className="w-4 h-4" />
            Add Brand
          </button>
          <button
            onClick={load}
            className="p-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 text-gray-500 transition-colors"
            title="Refresh"
          >
            <RefreshCw className="w-4 h-4" />
          </button>
          {withoutPage > 0 && (
            <button
              onClick={handleRegenAll}
              disabled={regenAll}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-bold shadow-lg shadow-blue-100 hover:opacity-90 transition-opacity disabled:opacity-60"
            >
              {regenAll ? <Loader2 className="w-4 h-4 animate-spin" /> : <TrendingUp className="w-4 h-4" />}
              Generate Missing ({withoutPage})
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
        <StatCard icon={Tag}          label="Total Brands"  value={brands.length} color="blue"   />
        <StatCard icon={CheckCircle2} label="SEO Ready"     value={withPage}      color="green"  />
        <StatCard icon={Clock}        label="Needs AI Page" value={withoutPage}   color="amber"  />
        <StatCard icon={Car}          label="Total Cars"    value={totalCars}     color="purple" />
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 mb-5 flex-wrap">
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search brands..."
          className="flex-1 min-w-[180px] max-w-xs px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
        />
        {(["all", "with-page", "without-page"] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={cn(
              "px-3 py-2 rounded-xl text-xs font-bold transition-all",
              filter === f
                ? "bg-blue-600 text-white"
                : "border border-gray-200 text-gray-600 hover:bg-gray-50"
            )}
          >
            {f === "all" ? "All" : f === "with-page" ? "SEO Ready" : "No AI Page"}
          </button>
        ))}
      </div>

      {/* Brand list */}
      {loading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-20 text-gray-400">
          <AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-40" />
          <p className="font-medium">No brands found</p>
        </div>
      ) : (
        <motion.div className="space-y-2">
          {filtered.map((b, i) => (
            <motion.div
              key={b.brandSlug}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.03 }}
            >
              <BrandRow brand={b} onRegenerate={handleRegenerate} />
            </motion.div>
          ))}
        </motion.div>
      )}
      <AddBrandModal
        open={addOpen}
        onClose={() => setAddOpen(false)}
        onCreated={load}
      />
    </div>
  );
}
