import type { Metadata } from "next";
import Link from "next/link";
import { MapPin, Building2, Tag, ChevronRight, Car } from "lucide-react";
import { fetchCities } from "@/lib/api";
import type { CityPageSummary } from "@/lib/types";

export const metadata: Metadata = {
  title: "New Cars by City — On-Road Prices, Dealers & Offers | DriveHub",
  description:
    "Explore new car on-road prices, authorised dealers, and latest offers in your city. Compare ex-showroom vs on-road prices across Mumbai, Delhi, Bangalore, Chennai and 25+ cities.",
};

export const revalidate = 3600; // ISR every hour

// ── helpers ───────────────────────────────────────────────────────────────────

const STATE_COLORS: Record<string, string> = {
  "Maharashtra":    "from-orange-500 to-red-500",
  "Karnataka":      "from-purple-500 to-indigo-500",
  "Tamil Nadu":     "from-teal-500 to-cyan-500",
  "Delhi":          "from-blue-500 to-sky-500",
  "Telangana":      "from-pink-500 to-rose-500",
  "West Bengal":    "from-green-500 to-emerald-500",
  "Gujarat":        "from-amber-500 to-yellow-500",
  "Rajasthan":      "from-red-500 to-orange-400",
  "Uttar Pradesh":  "from-indigo-500 to-violet-500",
  "Kerala":         "from-emerald-500 to-teal-500",
};

function gradient(state?: string) {
  return STATE_COLORS[state ?? ""] ?? "from-gray-400 to-gray-600";
}

// ── City card ─────────────────────────────────────────────────────────────────

function CityCard({ city }: { city: CityPageSummary }) {
  return (
    <Link
      href={`/cities/${city.slug}`}
      className="group relative rounded-[28px] overflow-hidden border border-gray-100 bg-white hover:border-blue-200 hover:shadow-xl hover:shadow-blue-100/30 transition-all duration-300"
    >
      {/* Coloured accent bar */}
      <div className={`h-2 bg-gradient-to-r ${gradient(city.state)}`} />

      <div className="p-5">
        <div className="flex items-start justify-between gap-2 mb-4">
          <div>
            <h2 className="text-lg font-black text-gray-900 group-hover:text-blue-600 transition-colors">
              {city.city}
            </h2>
            {city.state && (
              <p className="text-xs text-gray-400 font-medium mt-0.5">{city.state}</p>
            )}
          </div>
          <ChevronRight className="w-5 h-5 text-gray-300 group-hover:text-blue-500 group-hover:translate-x-0.5 transition-all mt-1 shrink-0" />
        </div>

        <div className="grid grid-cols-3 gap-2">
          <div className="rounded-xl bg-gray-50 p-2.5 text-center">
            <Building2 className="w-4 h-4 text-blue-500 mx-auto mb-1" />
            <p className="text-base font-black text-gray-900">{city.dealerCount ?? 0}</p>
            <p className="text-[9px] uppercase tracking-wide text-gray-400 font-bold">Dealers</p>
          </div>
          <div className="rounded-xl bg-gray-50 p-2.5 text-center">
            <Tag className="w-4 h-4 text-green-500 mx-auto mb-1" />
            <p className="text-base font-black text-gray-900">{city.offerCount ?? 0}</p>
            <p className="text-[9px] uppercase tracking-wide text-gray-400 font-bold">Offers</p>
          </div>
          <div className="rounded-xl bg-gray-50 p-2.5 text-center">
            <Car className="w-4 h-4 text-purple-500 mx-auto mb-1" />
            <p className="text-[9px] uppercase tracking-wide text-gray-400 font-bold mt-2">Prices</p>
            <p className="text-[9px] text-gray-400">Available</p>
          </div>
        </div>

        {city.updatedAt && (
          <p className="text-[9px] text-gray-300 mt-3">
            Updated {new Date(city.updatedAt).toLocaleDateString("en-IN", { month: "short", year: "numeric" })}
          </p>
        )}
      </div>
    </Link>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default async function CitiesPage() {
  const cities = await fetchCities().catch(() => [] as CityPageSummary[]);

  // Group by state for section headers
  const byState: Record<string, CityPageSummary[]> = {};
  for (const c of cities) {
    const state = c.state ?? "Other";
    byState[state] = [...(byState[state] ?? []), c];
  }

  const totalDealers = cities.reduce((s, c) => s + (c.dealerCount ?? 0), 0);
  const totalOffers  = cities.reduce((s, c) => s + (c.offerCount ?? 0), 0);

  return (
    <main className="min-h-screen bg-[#f5f7fb] pb-20">
      {/* ── Hero ── */}
      <div className="bg-gradient-to-br from-blue-600 via-indigo-600 to-purple-700 text-white">
        <div className="max-w-[1280px] mx-auto px-4 py-16">
          <p className="text-[10px] uppercase tracking-[0.3em] text-blue-200 font-black mb-3">
            City-wise Buying Guide
          </p>
          <h1 className="text-4xl md:text-5xl font-black mb-4 leading-tight">
            New Car Prices<br />
            <span className="text-blue-200">Across India</span>
          </h1>
          <p className="text-blue-100 text-lg max-w-xl leading-relaxed mb-8">
            On-road prices with RTO, insurance & TCS breakdown. Find authorised dealers,
            current offers, and waiting periods in your city.
          </p>

          {/* Stats */}
          <div className="flex flex-wrap gap-6">
            {[
              { value: cities.length,   label: "Cities" },
              { value: totalDealers,    label: "Dealers" },
              { value: totalOffers,     label: "Active Offers" },
            ].map(({ value, label }) => (
              <div key={label}>
                <p className="text-3xl font-black">{value.toLocaleString("en-IN")}+</p>
                <p className="text-blue-200 text-sm font-medium">{label}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="max-w-[1280px] mx-auto px-4 pt-10">
        {cities.length === 0 ? (
          /* Empty state — no pages generated yet */
          <div className="rounded-[32px] bg-white border border-gray-100 p-16 text-center shadow-sm">
            <MapPin className="w-12 h-12 text-gray-300 mx-auto mb-4" />
            <h2 className="text-xl font-black text-gray-700 mb-2">City pages are being generated</h2>
            <p className="text-gray-400 text-sm max-w-sm mx-auto">
              City pages are generated daily at 11:30 UTC. Check back shortly — or trigger
              generation from the admin panel.
            </p>
          </div>
        ) : Object.keys(byState).length > 0 ? (
          /* Grouped by state */
          Object.entries(byState).map(([state, stateCities]) => (
            <div key={state} className="mb-10">
              <h2 className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 mb-4 pl-1">
                {state}
              </h2>
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
                {stateCities.map((c) => (
                  <CityCard key={c.slug} city={c} />
                ))}
              </div>
            </div>
          ))
        ) : (
          /* Flat grid fallback */
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
            {cities.map((c) => (
              <CityCard key={c.slug} city={c} />
            ))}
          </div>
        )}
      </div>
    </main>
  );
}
