import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import {
  MapPin, Building2, Tag, Clock, Star, ChevronRight,
  Phone, Car, BadgePercent, Info,
} from "lucide-react";
import { fetchCityPage } from "@/lib/api";
import { resolveCarHeroImage } from "@/lib/carImage";
import type { CityPage, Dealer, CarOffer, CityPopularCar } from "@/lib/types";
import { formatPrice } from "@/lib/utils";

// ── Metadata ──────────────────────────────────────────────────────────────────

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const page = await fetchCityPage(slug).catch(() => null);
  if (!page) {
    return { title: "City not found | DriveHub" };
  }
  return {
    title: page.seoTitle ?? `New Cars in ${page.city} | DriveHub`,
    description: page.seoDescription,
    openGraph: { title: page.seoTitle ?? "", description: page.seoDescription },
  };
}

export const revalidate = 3600;

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

function fmtINR(n: number): string {
  if (n >= 10_000_000) return `₹${(n / 10_000_000).toFixed(2)} Cr`;
  if (n >= 100_000)    return `₹${(n / 100_000).toFixed(1)} L`;
  return `₹${n.toLocaleString("en-IN")}`;
}

const OFFER_COLOR: Record<string, string> = {
  cash:      "bg-green-50  border-green-200  text-green-700",
  exchange:  "bg-blue-50   border-blue-200   text-blue-700",
  bank:      "bg-purple-50 border-purple-200 text-purple-700",
  corporate: "bg-teal-50   border-teal-200   text-teal-700",
  loyalty:   "bg-amber-50  border-amber-200  text-amber-700",
  festive:   "bg-rose-50   border-rose-200   text-rose-700",
  other:     "bg-gray-50   border-gray-200   text-gray-700",
};
const OFFER_LABEL: Record<string, string> = {
  cash: "Cash", exchange: "Exchange", bank: "Bank",
  corporate: "Corporate", loyalty: "Loyalty", festive: "Festive", other: "Offer",
};

// ── Sub-components ────────────────────────────────────────────────────────────

function CarCard({ car, city }: { car: CityPopularCar; city: string }) {
  const href = car.slug ? `/cars/${car.slug}` : `/cars/${car.id}`;
  const heroSrc = resolveCarHeroImage(car);
  return (
    <Link
      href={href}
      className="group rounded-2xl border border-gray-100 bg-white hover:border-blue-200 hover:shadow-lg transition-all duration-200 overflow-hidden"
    >
      <div className="relative h-36 bg-gradient-to-br from-gray-50 to-gray-100">
        {heroSrc ? (
          <Image
            src={heroSrc}
            alt={car.name}
            fill
            className="object-contain p-3 group-hover:scale-105 transition-transform duration-300"
            sizes="(max-width: 640px) 50vw, 20vw"
          />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center text-gray-200 text-4xl font-black">
            {car.brand[0]}
          </div>
        )}
      </div>
      <div className="p-3">
        <p className="text-[9px] text-gray-400 font-black uppercase tracking-wide">{car.brand}</p>
        <h3 className="text-sm font-black text-gray-900 leading-tight group-hover:text-blue-600 transition-colors line-clamp-1">
          {car.name}
        </h3>
        <p className="text-sm font-black text-gray-900 mt-1.5">{fmtINR(car.priceMin)}</p>
        <p className="text-[9px] text-gray-400">Ex-showroom {city}</p>
        {car.rating && car.rating > 0 ? (
          <div className="flex items-center gap-1 mt-2">
            <Star className="w-3 h-3 fill-amber-400 text-amber-400" />
            <span className="text-xs font-bold text-gray-600">{car.rating.toFixed(1)}</span>
          </div>
        ) : null}
      </div>
    </Link>
  );
}

function DealerCard({ dealer }: { dealer: Dealer }) {
  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-5 hover:border-blue-200 hover:shadow-md transition-all">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2 mb-0.5">
            <p className="text-[9px] font-black uppercase tracking-wide text-blue-600">{dealer.brand}</p>
            {dealer.verified && (
              <span className="text-[9px] font-bold px-1.5 py-0.5 rounded-lg bg-green-50 text-green-600 border border-green-200">
                Verified
              </span>
            )}
          </div>
          <h3 className="text-sm font-black text-gray-900 leading-tight">{dealer.name}</h3>
        </div>
        {(dealer.rating ?? 0) > 0 && (
          <div className="flex items-center gap-1 shrink-0">
            <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
            <span className="text-sm font-black text-gray-700">{dealer.rating!.toFixed(1)}</span>
          </div>
        )}
      </div>

      {dealer.address && (
        <div className="flex items-start gap-1.5 text-xs text-gray-500 mb-2">
          <MapPin className="w-3.5 h-3.5 mt-0.5 text-gray-400 shrink-0" />
          <span className="leading-relaxed">{dealer.address}</span>
        </div>
      )}

      {dealer.services && dealer.services.length > 0 && (
        <div className="flex flex-wrap gap-1 mb-3">
          {dealer.services.map((s) => (
            <span key={s} className="text-[9px] font-bold px-2 py-0.5 rounded-lg bg-gray-100 text-gray-500 capitalize">
              {s}
            </span>
          ))}
        </div>
      )}

      {dealer.phone && (
        <a
          href={`tel:${dealer.phone}`}
          className="w-full flex items-center justify-center gap-2 py-2 rounded-xl border border-gray-200 text-xs font-bold text-gray-700 hover:border-blue-300 hover:text-blue-600 hover:bg-blue-50 transition-all"
        >
          <Phone className="w-3.5 h-3.5" />
          {dealer.phone}
        </a>
      )}
    </div>
  );
}

function OfferCard({ offer }: { offer: CarOffer }) {
  const color = OFFER_COLOR[offer.type] ?? OFFER_COLOR.other;
  return (
    <div className={`rounded-2xl border p-4 ${color}`}>
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <span className="text-[9px] font-black uppercase tracking-wide opacity-60">
            {OFFER_LABEL[offer.type] ?? offer.type}
            {offer.bankName ? ` · ${offer.bankName}` : ""}
          </span>
          <p className="text-sm font-black mt-0.5 leading-snug">{offer.title}</p>
          {offer.description && (
            <p className="text-xs mt-1 opacity-70 leading-relaxed line-clamp-2">{offer.description}</p>
          )}
          {offer.validTill && (
            <p className="text-[9px] mt-1.5 opacity-60 flex items-center gap-1">
              <Clock className="w-3 h-3" />
              Valid till {new Date(offer.validTill).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}
            </p>
          )}
        </div>
        <div className="text-right shrink-0">
          <p className="text-lg font-black">{fmtINR(offer.amount)}</p>
          <p className="text-[9px] opacity-60">savings</p>
        </div>
      </div>
    </div>
  );
}

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

export default async function CityDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const page = await fetchCityPage(slug).catch(() => null);

  if (!page) {
    return (
      <main className="min-h-screen bg-[#f5f7fb] flex items-center justify-center">
        <div className="text-center p-8">
          <MapPin className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h1 className="text-2xl font-black text-gray-700 mb-2">City not found</h1>
          <p className="text-gray-400 mb-6">
            We don&apos;t have a page for this city yet.
          </p>
          <Link
            href="/cities"
            className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-2xl font-bold hover:bg-blue-700 transition-colors"
          >
            Browse all cities
          </Link>
        </div>
      </main>
    );
  }

  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-12">
          {/* Breadcrumb */}
          <div className="flex items-center gap-1.5 text-xs text-blue-200 mb-6">
            <Link href="/" className="hover:text-white">Home</Link>
            <ChevronRight className="w-3 h-3" />
            <Link href="/cities" className="hover:text-white">Cities</Link>
            <ChevronRight className="w-3 h-3" />
            <span className="text-white font-semibold">{page.city}</span>
          </div>

          <p className="text-[10px] uppercase tracking-[0.3em] text-blue-200 font-black mb-2">
            {page.state}
          </p>
          <h1 className="text-4xl md:text-5xl font-black mb-4">
            New Cars in {page.city}
          </h1>
          <p className="text-blue-100 max-w-xl leading-relaxed mb-8">
            {page.seoDescription}
          </p>

          {/* Quick stats */}
          <div className="flex flex-wrap gap-6">
            {[
              { icon: Building2, value: page.dealerCount,       label: "Dealers" },
              { icon: Tag,       value: page.offerCount ?? 0,   label: "Active Offers" },
              { icon: Car,       value: page.popularCars.length, label: "Popular Models" },
            ].map(({ icon: Icon, value, label }) => (
              <div key={label} className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center">
                  <Icon className="w-5 h-5 text-blue-200" />
                </div>
                <div>
                  <p className="text-2xl font-black">{value}</p>
                  <p className="text-blue-200 text-xs">{label}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="max-w-[1280px] mx-auto px-4 pt-8 space-y-8">

        {/* ── Intro ── */}
        {page.intro && (
          <div className="rounded-[32px] bg-white border border-gray-200/60 p-6 md:p-8 shadow-sm">
            <p className="text-gray-700 leading-8 text-[15px] whitespace-pre-line">{page.intro}</p>
            <p className="text-[10px] text-gray-300 mt-4 flex items-center gap-1">
              <Info className="w-3 h-3" />
              Updated {page.updatedAt ? new Date(page.updatedAt).toLocaleDateString("en-IN", { month: "long", year: "numeric" }) : "recently"}
            </p>
          </div>
        )}

        {/* ── Popular cars ── */}
        {page.popularCars.length > 0 && (
          <section>
            <div className="flex items-center justify-between mb-5">
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-blue-600 font-black">Most Searched</p>
                <h2 className="text-2xl font-black text-gray-900">Popular Cars in {page.city}</h2>
              </div>
              <Link
                href="/cars"
                className="flex items-center gap-1 text-sm font-bold text-blue-600 hover:underline"
              >
                View all <ChevronRight className="w-4 h-4" />
              </Link>
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
              {page.popularCars.map((car) => (
                <CarCard key={car.id} car={car} city={page.city} />
              ))}
            </div>
          </section>
        )}

        {/* ── Current offers ── */}
        {page.topOffers.length > 0 && (
          <section>
            <div className="flex items-center gap-4 mb-5">
              <div className="w-10 h-10 rounded-2xl bg-green-100 flex items-center justify-center">
                <BadgePercent className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-[0.2em] text-green-600 font-black">Save More</p>
                <h2 className="text-2xl font-black text-gray-900">Current Offers in {page.city}</h2>
              </div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {page.topOffers.map((offer) => (
                <OfferCard key={offer.id} offer={offer} />
              ))}
            </div>
          </section>
        )}

        {/* ── Dealers ── */}
        {page.sampleDealers.length > 0 && (
          <section>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-4">
                <div className="w-10 h-10 rounded-2xl bg-blue-100 flex items-center justify-center">
                  <Building2 className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-[10px] uppercase tracking-[0.2em] text-blue-600 font-black">
                    Authorised
                  </p>
                  <h2 className="text-2xl font-black text-gray-900">
                    Dealers in {page.city}
                  </h2>
                </div>
              </div>
              <span className="text-sm font-bold text-gray-500">
                {page.dealerCount} dealers
              </span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {page.sampleDealers.map((d) => (
                <DealerCard key={d.id} dealer={d} />
              ))}
            </div>
            {page.dealerCount > page.sampleDealers.length && (
              <p className="text-sm text-gray-400 text-center mt-4">
                Showing {page.sampleDealers.length} of {page.dealerCount} dealers ·&nbsp;
                <Link href={`/cities/${slug}/dealers`} className="text-blue-600 font-bold hover:underline">
                  View all
                </Link>
              </p>
            )}
          </section>
        )}

        {/* ── Footer CTA ── */}
        <div className="rounded-[32px] bg-gradient-to-r from-blue-600 to-indigo-600 text-white p-8 flex flex-col sm:flex-row items-center justify-between gap-6">
          <div>
            <h2 className="text-2xl font-black mb-1">Ready to buy in {page.city}?</h2>
            <p className="text-blue-100 text-sm">
              Compare prices, check on-road cost, and connect with dealers — all in one place.
            </p>
          </div>
          <Link
            href="/cars"
            className="shrink-0 px-8 py-4 bg-white text-blue-600 rounded-2xl font-black hover:bg-blue-50 transition-colors shadow-xl"
          >
            Browse Cars
          </Link>
        </div>
      </div>
    </main>
  );
}
