import type { Metadata } from "next";
import Link from "next/link";
import { getPayload } from 'payload'
import config from '@payload-config'
import { normalizeCar, type PayloadCar } from "@/lib/payload-helpers";
import { SITE } from "@/lib/seo";

export const revalidate = 3600

const DEFAULT_OG = "/media/ferrari-f8-tributo-rental-dubai-02.webp"

export const metadata: Metadata = {
  title: "Car Rental Price List Dubai | NCK Car Rental",
  description: "Complete car rental price list in Dubai. Compare daily rental rates for luxury, SUV, sports, and economy cars. From AED 150/day.",
  alternates: { canonical: `${SITE.domain}/car-price-list/` },
  robots: { index: true, follow: true },
  openGraph: {
    title:       "Car Rental Price List Dubai | NCK Car Rental",
    description: "Compare daily rental rates for luxury, sports, SUV & economy cars in Dubai. Transparent pricing, no hidden fees.",
    url:         `${SITE.domain}/car-price-list/`,
    siteName:    "NCK Car Rental",
    locale:      "en_AE",
    images:      [{ url: DEFAULT_OG, width: 1200, height: 630, alt: "Car Rental Price List Dubai - NCK Car Rental" }],
  },
  twitter: {
    card:        "summary_large_image",
    title:       "Car Rental Price List Dubai | NCK Car Rental",
    description: "Daily rental rates for 94+ cars in Dubai. Luxury from AED 500/day, economy from AED 150/day.",
    images:      [DEFAULT_OG],
  },
};

const CATEGORY_ORDER = ["luxury", "sports", "suv", "convertible", "coupe", "sedan"];
const CATEGORY_LABELS: Record<string, string> = {
  luxury: "Luxury Cars", sports: "Sports Cars", suv: "SUV",
  convertible: "Convertible", coupe: "Coupe", sedan: "Sedan",
};

export default async function CarPriceListPage() {
  const payload = await getPayload({ config })
  const { docs } = await payload.find({
    collection: 'cars', depth: 1, limit: 500, pagination: false,
  })
  const allCars = (docs as unknown as PayloadCar[]).map(doc => normalizeCar(doc))

  const sorted = [...allCars].sort((a, b) => {
    const ci = CATEGORY_ORDER.indexOf(a.category) - CATEGORY_ORDER.indexOf(b.category);
    if (ci !== 0) return ci;
    return (a.priceDay ?? 999999) - (b.priceDay ?? 999999);
  });

  const grouped = CATEGORY_ORDER.reduce<Record<string, typeof allCars>>((acc, cat) => {
    acc[cat] = sorted.filter(c => c.category === cat);
    return acc;
  }, {});

  const tableJsonLd = {
    "@context": "https://schema.org",
    "@type": "ItemList",
    name: "Car Rental Price List Dubai",
    numberOfItems: allCars.length,
    itemListElement: allCars
      .filter(c => c.priceDay)
      .sort((a, b) => (a.priceDay ?? 0) - (b.priceDay ?? 0))
      .slice(0, 20)
      .map((c, i) => ({
        "@type": "ListItem",
        position: i + 1,
        name: c.title,
        url: `${SITE.domain}/car/${c.slug}/`,
      })),
  };

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

      <div className="bg-navy-900 text-white py-10">
        <div className="section-wrap">
          <nav className="flex items-center gap-1.5 text-xs text-navy-300 mb-3">
            <Link href="/" className="hover:text-white">Home</Link>
            <span>/</span>
            <span>Car Rental Price List</span>
          </nav>
          <h1 className="text-3xl font-black mb-2">Car Rental Price List Dubai</h1>
          <p className="text-navy-300 text-sm max-w-xl">
            Transparent daily rental rates for all {allCars.length}+ cars. No hidden fees. Prices in AED/day.
          </p>
        </div>
      </div>

      <div className="section-wrap py-8">
        {/* Category anchor links */}
        <div className="flex flex-wrap gap-2 mb-8">
          {CATEGORY_ORDER.filter(c => grouped[c]?.length > 0).map(cat => (
            <a key={cat} href={`#${cat}`} className="pill-tab text-sm">
              {CATEGORY_LABELS[cat]} ({grouped[cat].length})
            </a>
          ))}
        </div>

        {/* Tables per category */}
        {CATEGORY_ORDER.filter(cat => grouped[cat]?.length > 0).map(cat => (
          <section key={cat} id={cat} className="mb-10">
            <h2 className="text-lg font-black text-[#1a1f2e] mb-3">{CATEGORY_LABELS[cat]} Rental Prices</h2>
            <div className="overflow-x-auto rounded-2xl border border-[#e2e6ed]">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-[#f8f9fb] border-b border-[#e2e6ed]">
                    <th className="text-left px-4 py-3 text-xs font-bold text-[#5c6472] uppercase tracking-wide">Car</th>
                    <th className="text-left px-4 py-3 text-xs font-bold text-[#5c6472] uppercase tracking-wide">Brand</th>
                    <th className="text-left px-4 py-3 text-xs font-bold text-[#5c6472] uppercase tracking-wide">Seats</th>
                    <th className="text-left px-4 py-3 text-xs font-bold text-[#5c6472] uppercase tracking-wide">Gearbox</th>
                    <th className="text-right px-4 py-3 text-xs font-bold text-[#5c6472] uppercase tracking-wide">Price/Day</th>
                    <th className="px-4 py-3"></th>
                  </tr>
                </thead>
                <tbody>
                  {grouped[cat].map((car, i) => (
                    <tr
                      key={car.slug}
                      className={`border-b border-[#e2e6ed] last:border-0 hover:bg-[#f8f9fb] transition-colors ${i % 2 === 0 ? "bg-white" : "bg-[#fafbfc]"}`}
                    >
                      <td className="px-4 py-3">
                        <Link href={`/car/${car.slug}`} className="font-semibold text-[#1a1f2e] hover:text-brand">
                          {car.title}
                        </Link>
                        {car.noDeposit && (
                          <span className="ml-2 text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full font-semibold">
                            No Deposit
                          </span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        {car.brandSlug ? (
                          <Link href={`/carbrand/${car.brandSlug}`} className="text-[#5c6472] hover:text-brand">
                            {car.brand}
                          </Link>
                        ) : (
                          <span className="text-[#5c6472]">{car.brand}</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-[#5c6472]">{car.passengers}</td>
                      <td className="px-4 py-3 text-[#5c6472]">{car.transmission}</td>
                      <td className="px-4 py-3 text-right">
                        <span className="font-black text-brand text-base">
                          AED {car.priceDay?.toLocaleString() ?? "N/A"}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <Link
                          href={`/car/${car.slug}`}
                          className="text-xs font-semibold text-brand border border-brand/30 px-3 py-1 rounded-full hover:bg-brand hover:text-white transition-colors whitespace-nowrap"
                        >
                          Book Now
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ))}

        <section className="mt-8 bg-[#f8f9fb] rounded-2xl p-6 border border-[#e2e6ed]">
          <h2 className="text-xl font-black text-[#1a1f2e] mb-3">Car Rental Prices in Dubai</h2>
          <div className="grid sm:grid-cols-2 gap-4 text-sm text-[#5c6472] leading-relaxed">
            <div>
              <p className="mb-3">
                Rental prices in Dubai vary more than in most cities. A standard sedan starts around AED 150 a day;
                mid-size SUVs run AED 300–700 depending on the model; sports and luxury cars range from AED 500 up
                to AED 6,500 for an exotic. The price reflects the car. Delivery and insurance are included across
                the NCK Car Rental fleet.
              </p>
              <p>
                Basic insurance is included in every rate shown. Free delivery covers all of Dubai: Downtown,
                Marina, Palm Jumeirah, JBR, DIFC, Business Bay, and both airports.
              </p>
            </div>
            <div>
              <p className="mb-3">
                Daily, weekly, and monthly rentals are all available. Monthly rates work out roughly 25–30% cheaper
                per day than the daily rate. No deposit is required on a selection of models. Check the individual
                car listing.
              </p>
              <p>
                Rates shown are the standard daily price. Message NCK Car Rental on WhatsApp for weekly and monthly
                quotes, corporate fleet arrangements, and event hire.
              </p>
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
