"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { Car, ChevronRight, Search, TrendingUp } from "lucide-react";
import { fetchBestCarsCategories } from "@/lib/api";
import type { BestCarsCategory } from "@/lib/types";

const CATEGORY_COLORS: Record<string, string> = {
  "best-cars-under-5-lakh":  "from-green-500 to-emerald-600",
  "best-cars-under-10-lakh": "from-blue-500 to-cyan-600",
  "best-cars-under-15-lakh": "from-indigo-500 to-blue-600",
  "best-cars-under-20-lakh": "from-violet-500 to-purple-600",
  "best-electric-cars":      "from-green-400 to-teal-600",
  "best-suv-under-15-lakh":  "from-orange-500 to-amber-600",
  "best-suv-cars":           "from-red-500 to-rose-600",
  "best-family-cars":        "from-pink-500 to-rose-600",
  "best-mileage-cars":       "from-yellow-500 to-orange-500",
  "best-city-cars":          "from-sky-500 to-blue-600",
  "best-automatic-cars":     "from-slate-600 to-gray-700",
  "best-diesel-cars":        "from-stone-600 to-zinc-700",
  "best-luxury-cars":        "from-amber-600 to-yellow-600",
  "best-hybrid-cars":        "from-teal-500 to-cyan-600",
  "best-7-seater-cars":      "from-blue-600 to-indigo-700",
  "best-sedan-cars":         "from-purple-500 to-violet-600",
  "best-cng-cars":           "from-emerald-500 to-green-700",
};

function CategoryCard({ cat, index }: { cat: BestCarsCategory; index: number }) {
  const gradient = CATEGORY_COLORS[cat.slug] ?? "from-blue-500 to-indigo-600";
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.05 }}
    >
      <Link href={`/best-cars/${cat.slug}`}>
        <div className="group relative bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-xl hover:border-transparent transition-all duration-300 overflow-hidden cursor-pointer h-full">
          {/* Gradient stripe at top */}
          <div className={`h-2 bg-gradient-to-r ${gradient}`} />

          <div className="p-5">
            {/* Icon + title */}
            <div className="flex items-start gap-3 mb-4">
              <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${gradient} flex items-center justify-center text-2xl flex-shrink-0`}>
                {cat.icon}
              </div>
              <div>
                <h3 className="font-bold text-gray-900 text-base leading-tight group-hover:text-blue-600 transition-colors">
                  {cat.h1}
                </h3>
                <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">
                  {cat.description}
                </p>
              </div>
            </div>

            <div className="flex items-center justify-between">
              <span className="text-sm font-semibold text-gray-600">
                {cat.carCount > 0 ? (
                  <span className="text-blue-600">{cat.carCount} cars</span>
                ) : (
                  <span className="text-gray-400">Loading...</span>
                )}
              </span>
              <div className="flex items-center gap-1.5">
                {cat.hasPage && (
                  <span className="text-xs bg-green-50 text-green-700 font-medium px-2 py-0.5 rounded-full">
                    ✓ SEO ready
                  </span>
                )}
                <ChevronRight className="w-4 h-4 text-gray-400 group-hover:text-blue-500 group-hover:translate-x-1 transition-all" />
              </div>
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}

export default function BestCarsPage() {
  const [categories, setCategories] = useState<BestCarsCategory[]>([]);
  const [filtered, setFiltered] = useState<BestCarsCategory[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchBestCarsCategories()
      .then((res) => {
        setCategories(res.categories);
        setFiltered(res.categories);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (!search.trim()) {
      setFiltered(categories);
    } else {
      const q = search.toLowerCase();
      setFiltered(
        categories.filter(
          (c) => c.title.toLowerCase().includes(q) || c.description.toLowerCase().includes(q)
        )
      );
    }
  }, [search, categories]);

  // Group by theme
  const budgetCats = filtered.filter((c) => c.slug.includes("under") || c.slug.includes("luxury"));
  const typeCats = filtered.filter(
    (c) =>
      c.slug.includes("suv") ||
      c.slug.includes("sedan") ||
      c.slug.includes("hatchback") ||
      c.slug.includes("city") ||
      c.slug.includes("family") ||
      c.slug.includes("7-seater")
  );
  const fuelCats = filtered.filter(
    (c) =>
      c.slug.includes("electric") ||
      c.slug.includes("diesel") ||
      c.slug.includes("hybrid") ||
      c.slug.includes("cng")
  );
  const featureCats = filtered.filter(
    (c) => c.slug.includes("automatic") || c.slug.includes("mileage")
  );

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero */}
      <div className="bg-gradient-to-br from-blue-900 via-indigo-900 to-purple-900 text-white pt-24 pb-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }}>
            <span className="inline-flex items-center gap-2 bg-white/10 backdrop-blur px-4 py-2 rounded-full text-sm font-medium mb-6">
              <TrendingUp className="w-4 h-4" />
              Programmatic SEO Pages
            </span>
            <h1 className="text-4xl md:text-5xl font-black mb-4 leading-tight">
              Best Cars in India 2026
            </h1>
            <p className="text-blue-100 text-lg max-w-2xl mx-auto mb-8">
              Curated lists of the best cars by budget, type, fuel and features — updated daily.
            </p>
          </motion.div>

          {/* Search */}
          <div className="max-w-md mx-auto">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-300 w-5 h-5" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search categories..."
                className="w-full pl-12 pr-4 py-3 rounded-xl bg-white/10 backdrop-blur border border-white/20 text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-white/30"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
            {Array.from({ length: 12 }).map((_, i) => (
              <div key={i} className="bg-white rounded-2xl border border-gray-100 overflow-hidden animate-pulse">
                <div className="h-2 bg-gray-200" />
                <div className="p-5 space-y-3">
                  <div className="flex gap-3">
                    <div className="w-12 h-12 bg-gray-200 rounded-xl" />
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-3/4" />
                      <div className="h-3 bg-gray-100 rounded w-full" />
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <>
            {/* By Budget */}
            {budgetCats.length > 0 && (
              <section className="mb-12">
                <h2 className="text-2xl font-bold text-gray-900 mb-5">💰 By Budget</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                  {budgetCats.map((c, i) => <CategoryCard key={c.slug} cat={c} index={i} />)}
                </div>
              </section>
            )}

            {/* By Body Type */}
            {typeCats.length > 0 && (
              <section className="mb-12">
                <h2 className="text-2xl font-bold text-gray-900 mb-5">🚗 By Car Type</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                  {typeCats.map((c, i) => <CategoryCard key={c.slug} cat={c} index={i} />)}
                </div>
              </section>
            )}

            {/* By Fuel */}
            {fuelCats.length > 0 && (
              <section className="mb-12">
                <h2 className="text-2xl font-bold text-gray-900 mb-5">⛽ By Fuel Type</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                  {fuelCats.map((c, i) => <CategoryCard key={c.slug} cat={c} index={i} />)}
                </div>
              </section>
            )}

            {/* By Feature */}
            {featureCats.length > 0 && (
              <section className="mb-12">
                <h2 className="text-2xl font-bold text-gray-900 mb-5">✨ By Feature</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                  {featureCats.map((c, i) => <CategoryCard key={c.slug} cat={c} index={i} />)}
                </div>
              </section>
            )}

            {filtered.length === 0 && (
              <div className="text-center py-20 text-gray-500">
                <Car className="w-12 h-12 mx-auto mb-4 opacity-30" />
                <p className="text-lg font-medium">No categories match your search</p>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
