"use client";

import { useEffect, useState, useCallback } from "react";
import { motion } from "framer-motion";
import {
  TrendingUp, RefreshCw, Loader2, CheckCircle2, Clock,
  AlertCircle, ExternalLink, Car, Sparkles,
} from "lucide-react";
import { fetchBestCarsCategories, generateBestCarsPage } from "@/lib/api";
import type { BestCarsCategory } 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-4 sm:p-5 shadow-[0_4px_20px_rgba(0,0,0,0.05)] min-w-0">
      <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 tabular-nums break-words">{value}</p>
      <p className="text-xs font-bold text-gray-500 mt-1 break-words">{label}</p>
    </div>
  );
}

function CategoryRow({
  cat,
  onRegenerate,
}: {
  cat: BestCarsCategory;
  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(cat.slug);
      setDone(true);
      setTimeout(() => setDone(false), 3000);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4 p-3 sm:p-4 bg-white rounded-2xl border border-gray-100 hover:border-gray-200 transition-colors min-w-0">
      {/* Icon + Info */}
      <div className="flex items-start gap-3 sm:gap-4 flex-1 min-w-0">
        <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-xl flex-shrink-0">
          {cat.icon}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap min-w-0">
            <span className="font-bold text-gray-900 text-sm min-w-0 break-words">{cat.h1}</span>
            {cat.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 flex-shrink-0">
                <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 flex-shrink-0">
                <Clock className="w-3 h-3" /> No Content
              </span>
            )}
          </div>
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-gray-500 min-w-0">
            <span className="flex items-center gap-1 shrink-0"><Car className="w-3 h-3" />{cat.carCount} cars</span>
            <span className="text-gray-300 hidden sm:inline">·</span>
            <span className="text-gray-400 min-w-0 break-all">{cat.slug}</span>
            {cat.updatedAt && (
              <>
                <span className="text-gray-300 hidden sm:inline">·</span>
                <span className="shrink-0">Updated {new Date(cat.updatedAt).toLocaleDateString("en-IN")}</span>
              </>
            )}
          </div>
          {error && <p className="text-xs text-red-500 mt-1 break-words">{error}</p>}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-2 flex-shrink-0 w-full sm:w-auto">
        <a
          href={`/best-cars/${cat.slug}`}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center justify-center min-h-[44px] min-w-[44px] p-2 rounded-xl hover:bg-gray-100 text-gray-400 hover:text-blue-600 transition-colors"
          title="View category page"
        >
          <ExternalLink className="w-4 h-4" />
        </a>
        <button
          onClick={handleRegen}
          disabled={loading}
          title="Regenerate AI content"
          className={cn(
            "flex flex-1 sm:flex-initial items-center justify-center gap-1.5 px-3 py-2 min-h-[44px] 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>
  );
}

export default function AdminBestCarsPage() {
  const [categories, setCategories] = useState<BestCarsCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [regenAll, setRegenAll] = useState(false);

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

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

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

  async function handleRegenAll() {
    const missing = categories.filter((c) => !c.hasPage);
    if (!missing.length) return;
    setRegenAll(true);
    for (const c of missing) {
      try { await generateBestCarsPage(c.slug); } catch { /* quota — skip */ }
    }
    await load();
    setRegenAll(false);
  }

  const withPage    = categories.filter((c) => c.hasPage).length;
  const withoutPage = categories.filter((c) => !c.hasPage).length;
  const totalCars   = categories.reduce((s, c) => s + c.carCount, 0);

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-5xl mx-auto min-w-0 overflow-x-hidden pb-[calc(1.5rem+env(safe-area-inset-bottom,0px))]">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between min-w-0">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 break-words">Best Cars / Programmatic SEO</h1>
          <p className="text-sm text-gray-500 mt-0.5 break-words">AI-generated pages for 17 best-car categories</p>
        </div>
        <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
          <button
            onClick={load}
            className="inline-flex items-center justify-center min-h-[44px] min-w-[44px] 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 flex-1 sm:flex-initial items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] 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 min-w-0"
            >
              {regenAll ? <Loader2 className="w-4 h-4 animate-spin shrink-0" /> : <Sparkles className="w-4 h-4 shrink-0" />}
              <span className="truncate">Generate Missing ({withoutPage})</span>
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-6 min-w-0">
        <StatCard icon={TrendingUp}   label="Categories"   value={categories.length} color="blue"   />
        <StatCard icon={CheckCircle2} label="SEO Ready"    value={withPage}          color="green"  />
        <StatCard icon={Clock}        label="Needs Content" value={withoutPage}      color="amber"  />
        <StatCard icon={Car}          label="Total Cars"   value={totalCars}         color="purple" />
      </div>

      {/* Category list */}
      {loading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
        </div>
      ) : categories.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 categories found</p>
        </div>
      ) : (
        <motion.div className="space-y-2 min-w-0">
          {categories.map((cat, i) => (
            <motion.div
              key={cat.slug}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.03 }}
              className="min-w-0"
            >
              <CategoryRow cat={cat} onRegenerate={handleRegenerate} />
            </motion.div>
          ))}
        </motion.div>
      )}
    </div>
  );
}
