import { Suspense } from "react";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { fetchCarById } from "@/lib/api";
import { getCarHeroImage } from "@/lib/carImage";
import { resolveUploadUrl } from "@/lib/uploadUrl";
import { formatPrice } from "@/lib/utils";
import CarDetailClient from "./CarDetailClient";
import { CarDetailSkeleton } from "@/components/ui/Skeletons";
import type { Car } from "@/lib/types";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://drivehub.in";

interface Props { params: { id: string } }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  try {
    const car = await fetchCarById(params.id);
    const rawHero = getCarHeroImage(car);
    const heroImage = rawHero ? resolveUploadUrl(rawHero) : "";
    const title = `${car.name} Price, Specs, Variants & Review | DriveHub`;
    const yearStr = car.year ? ` (${car.year})` : "";
    const description = `${car.name}${yearStr} price starts at ${formatPrice(car.priceMin)} (ex-showroom). Check full specifications, variants, mileage, images, and expert review.`;
    return {
      title,
      description,
      keywords: [car.name, car.brand, car.fuelType, car.transmission, car.bodyType, "price", "specs", "review", "india"].filter(Boolean) as string[],
      openGraph: {
        title,
        description,
        type: "website",
        url: `${SITE_URL}/cars/${params.id}`,
        siteName: "DriveHub",
        images: heroImage ? [{ url: heroImage, alt: car.name }] : [],
      },
      twitter: {
        card: "summary_large_image",
        title,
        description,
        images: heroImage ? [heroImage] : [],
      },
      alternates: {
        canonical: `${SITE_URL}/cars/${params.id}`,
      },
    };
  } catch {
    return { title: "Car Not Found | DriveHub" };
  }
}

/** JSON-LD structured data: Product + BreadcrumbList */
function CarJsonLd({ car }: { car: Car }) {
  const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://drivehub.in";
  const rawHero = getCarHeroImage(car);
  const heroImage = rawHero ? resolveUploadUrl(rawHero) : "";

  const schema = {
    "@context": "https://schema.org",
    "@type": "Product",
    name: car.name,
    description: car.overview ?? `${car.name} — ${car.fuelType}, ${car.transmission}`,
    brand: {
      "@type": "Brand",
      name: car.brand,
    },
    image: heroImage ? [heroImage] : [],
    url: `${BASE_URL}/cars/${car.id}`,
    offers: {
      "@type": "AggregateOffer",
      priceCurrency: "INR",
      lowPrice: (car.priceMin * 100000).toString(),
      highPrice: (car.priceMax * 100000).toString(),
      offerCount: car.variants?.length ?? 1,
      availability: "https://schema.org/InStock",
    },
    ...(car.rating > 0 && {
      aggregateRating: {
        "@type": "AggregateRating",
        ratingValue: car.rating.toFixed(1),
        reviewCount: car.reviewCount || 1,
        bestRating: "5",
        worstRating: "1",
      },
    }),
  };

  const breadcrumb = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: BASE_URL },
      { "@type": "ListItem", position: 2, name: "Cars", item: `${BASE_URL}/cars` },
      { "@type": "ListItem", position: 3, name: car.brand, item: `${BASE_URL}/cars?brand=${encodeURIComponent(car.brand)}` },
      { "@type": "ListItem", position: 4, name: car.name, item: `${BASE_URL}/cars/${car.id}` },
    ],
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumb) }}
      />
    </>
  );
}

async function CarDetailContent({ id }: { id: string }) {
  let car: Car;
  try {
    car = await fetchCarById(id);
  } catch {
    notFound();
  }
  return (
    <>
      <CarJsonLd car={car} />
      <CarDetailClient car={car} />
    </>
  );
}

export default function CarDetailPage({ params }: Props) {
  return (
    <Suspense fallback={<CarDetailSkeleton />}>
      <CarDetailContent id={params.id} />
    </Suspense>
  );
}
