import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { MapPin } from "lucide-react";

import { BlogSection } from "@/components/BlogSection";
import { BrandsWeServeSection } from "@/components/BrandsWeServeSection";
import { HeroSection } from "@/components/HeroSection";
import { HomeFaqSection } from "@/components/HomeFaqSection";
import { LocationPageActivator } from "@/components/LocationPageActivator";
import { ServicesSection } from "@/components/ServiceCard";
import { HowItWorksSection } from "@/components/StepCard";
import { TestimonialsSection } from "@/components/Testimonials";
import { TrustStatsSection } from "@/components/TrustStatsSection";
import { WhyChooseUsSection } from "@/components/WhyChooseUsSection";
import {
  getLocationLandmarkPage,
  getLocationLandmarkPages,
  type LocationLandmarkPage,
} from "@/lib/location-pages";
import { JsonLd, breadcrumbJsonLd, serviceJsonLd } from "@/lib/seo";

type LandmarkPageProps = {
  params: Promise<{
    locationSlug: string;
    landmarkSlug: string;
  }>;
};

export async function generateMetadata({ params }: LandmarkPageProps): Promise<Metadata> {
  const { locationSlug, landmarkSlug } = await params;
  const landmark = await getLocationLandmarkPage(locationSlug, landmarkSlug);

  if (!landmark) {
    return {
      title: "Service Location",
      robots: {
        index: false,
        follow: false,
      },
    };
  }

  return {
    title: `Doorstep Vehicle Service in ${landmark.name}, ${landmark.locationName}`,
    description: `Book Ride N Revive doorstep car service, bike service, AC, battery, tyre, and engine support in ${landmark.name}, ${landmark.locationName}.`,
    alternates: {
      canonical: `/cities/${landmark.locationSlug}/${landmark.slug}`,
    },
  };
}

export async function generateStaticParams() {
  const landmarks = await getLocationLandmarkPages();

  return landmarks.map((landmark) => ({
    locationSlug: landmark.locationSlug,
    landmarkSlug: landmark.slug,
  }));
}

export default async function CityLandmarkPage({ params }: LandmarkPageProps) {
  const { locationSlug, landmarkSlug } = await params;
  const landmark = await getLocationLandmarkPage(locationSlug, landmarkSlug);

  if (!landmark) {
    notFound();
  }

  const locationDisplayName = getLandmarkLocationDisplayName(landmark);

  return (
    <>
      <LocationPageActivator locationId={landmark.locationId} displayName={locationDisplayName} />
      <JsonLd
        data={[
          serviceJsonLd({
            name: `Doorstep vehicle service in ${landmark.name}, ${landmark.locationName}`,
            description: `Ride N Revive doorstep car and bike service support in ${landmark.name}, ${landmark.locationName}.`,
            path: `/cities/${landmark.locationSlug}/${landmark.slug}/`,
            serviceType: "Vehicle service landmark",
            areaServed: `${landmark.name}, ${landmark.locationName}`,
          }),
          breadcrumbJsonLd([
            { name: "Home", path: "/" },
            { name: "Cities", path: "/cities/" },
            { name: landmark.locationName, path: `/cities/${landmark.locationSlug}/` },
            {
              name: landmark.name,
              path: `/cities/${landmark.locationSlug}/${landmark.slug}/`,
            },
          ]),
        ]}
      />
      <HeroSection />
      <LandmarkIntro landmark={landmark} locationDisplayName={locationDisplayName} />
      <ServicesSection />
      <HowItWorksSection />
      <WhyChooseUsSection />
      <TrustStatsSection />
      <HomeFaqSection />
      <TestimonialsSection />
      <BlogSection />
      <BrandsWeServeSection />
    </>
  );
}

function LandmarkIntro({
  landmark,
  locationDisplayName,
}: {
  landmark: LocationLandmarkPage;
  locationDisplayName: string;
}) {
  return (
    <section className="border-b border-border bg-white font-['Space_Grotesk']">
      <div className="mx-auto max-w-7xl px-4 py-8 md:px-6">
        <div className="flex flex-col gap-4 rounded-lg border border-border bg-slate-50 p-5 sm:flex-row sm:items-start">
          <span className="grid h-11 w-11 shrink-0 place-items-center rounded-md bg-primary/10 text-primary">
            <MapPin className="h-5 w-5" />
          </span>
          <div>
            <p className="text-xs font-black uppercase tracking-[0.18em] text-primary">
              Location-specific service
            </p>
            <h1 className="mt-2 text-2xl font-black tracking-tight text-foreground md:text-3xl">
              Doorstep vehicle service in {locationDisplayName}
            </h1>
            <p className="mt-3 max-w-3xl text-sm font-semibold leading-6 text-muted-foreground md:text-base">
              This page is focused on {formatLandmarkName(landmark.name)}. Pricing and availability
              continue to use the parent service city, {landmark.locationName}, from the service
              locations database.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

function getLandmarkLocationDisplayName(landmark: LocationLandmarkPage) {
  return `${landmark.locationName} (${formatLandmarkName(landmark.name)})`;
}

function formatLandmarkName(value: string) {
  const cleanedValue = value.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
  const sectorMatch = cleanedValue.match(/^sector\s*-?\s*(.+)$/i);

  if (sectorMatch) {
    return `Sector -${sectorMatch[1].trim()}`;
  }

  return cleanedValue
    .split(" ")
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}
