import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import prisma from "@/lib/prisma";
import EscortCard from "@/components/shared/escort-card";
import { withAvatarUrls } from "@/lib/media";

// Service slug → enjoys table name mapping
const serviceMap: Record<
  string,
  { name: string; displayName: string; description: string }
> = {
  gfe: {
    name: "GFE",
    displayName: "Girlfriend Experience (GFE)",
    description:
      "The Girlfriend Experience (GFE) offers an intimate, romantic encounter that feels natural and genuine. Unlike a standard booking, a GFE session is designed to replicate the warmth, affection, and emotional connection of a real relationship. Expect unhurried conversation, affectionate touches, kissing, and a relaxed atmosphere where both parties enjoy each other's company. GFE providers are skilled at creating a comfortable, judgement-free space where you can truly unwind. Whether it is a dinner date that leads somewhere private or a cosy evening in, the emphasis is always on chemistry, authenticity, and mutual enjoyment. Many clients describe the Girlfriend Experience as the most fulfilling way to spend time with a companion — because it goes beyond the physical and into genuine human connection.",
  },
  bdsm: {
    name: "BDSM",
    displayName: "BDSM",
    description:
      "BDSM encompasses a wide range of consensual power exchange activities including bondage, discipline, dominance, submission, sadism, and masochism. Escorts who offer BDSM services are experienced practitioners who understand the importance of communication, boundaries, and aftercare. Whether you are a curious beginner or an experienced player, you will find providers who can guide you through everything from light restraint and role-play to more intense sessions involving impact play, sensory deprivation, and protocol-based dynamics. Safety and consent are always paramount — reputable BDSM providers will discuss limits, safe words, and expectations before any session begins. Explore your desires in a controlled, professional environment with someone who truly understands the craft.",
  },
  massage: {
    name: "Massage",
    displayName: "Massage",
    description:
      "Erotic and sensual massage services provide relaxation and intimacy in equal measure. These sessions blend professional bodywork techniques with a sensual, intimate touch that goes far beyond what you would find at a standard spa. Providers trained in erotic massage use slow, deliberate strokes, warm oils, and body-to-body contact to release tension, stimulate the senses, and create deep physical pleasure. Whether you are looking for a tantric experience, a nuru massage, or a classic sensual rubdown, the escorts listed here specialise in making you feel completely at ease. Massage sessions are ideal for first-time clients who want a low-pressure, high-pleasure introduction to the world of adult companionship.",
  },
  "dinner-dates": {
    name: "Dinner Dates",
    displayName: "Dinner Dates",
    description:
      "Dinner date escorts are the perfect companions for an evening out. Whether you are visiting a new city and want company at a top restaurant, attending a social event, or simply craving stimulating conversation over a great meal, these providers excel at making you feel like the most important person in the room. Dinner date escorts are well-presented, articulate, and socially confident — they blend seamlessly into any setting from a Michelin-starred restaurant to a casual wine bar. Many clients book dinner dates as a prelude to a longer evening together, combining fine dining with private time afterwards. It is the complete companion experience: public charm followed by private intimacy.",
  },
  companionship: {
    name: "Travel Companion",
    displayName: "Travel Companion",
    description:
      "Travel companion escorts join you on trips, holidays, and business travel. Imagine exploring a new city, relaxing on a beach, or attending a conference with an attractive, engaging companion by your side. Travel escorts are adaptable, well-travelled, and comfortable in a wide range of social situations. They handle everything from casual sightseeing to formal dinners with ease. Bookings typically range from a full day to an entire week, and rates are agreed upon in advance to cover the companion's time, travel expenses, and accommodation. If you value company, conversation, and connection while you travel, a travel companion transforms an ordinary trip into an unforgettable experience.",
  },
  anal: {
    name: "Anal",
    displayName: "Anal",
    description:
      "Escorts who offer anal services provide a safe, professional, and pleasurable experience for clients interested in this intimate activity. Communication is key — providers will discuss preferences, comfort levels, and boundaries before any session to ensure a mutually enjoyable encounter. These escorts are experienced, patient, and attentive, making them an excellent choice whether this is something you have enjoyed before or something you are exploring for the first time. Hygiene, safety, and discretion are always prioritised. Browse verified providers who list anal among their services and read reviews from other clients to find the right match for your preferences.",
  },
  oral: {
    name: "Oral",
    displayName: "Oral",
    description:
      "Oral services are among the most popular offerings on AdultWorld.ai. Escorts who provide oral experiences are attentive, skilled, and focused on delivering genuine pleasure. Whether you are looking for a passionate, unhurried encounter or something more intense, the providers listed here have been rated and reviewed by other clients for their expertise. As with all services, open communication about preferences and boundaries ensures the best possible experience for both parties. Browse profiles, check reviews, and connect with verified escorts who offer oral services in your area. Discretion and professionalism are guaranteed across every booking on the platform.",
  },
};

const validSlugs = Object.keys(serviceMap);

type Props = {
  params: Promise<{ service: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { service } = await params;
  const serviceInfo = serviceMap[service];

  if (!serviceInfo) {
    return { title: "Service Not Found — AdultWorld.ai" };
  }

  const count = await prisma.enjoyUser.count({
    where: {
      enjoy: { name: serviceInfo.name },
      user: { user_type: "escort", active: true, banned_at: null },
    },
  });

  return {
    title: `${serviceInfo.displayName} Escorts (${count.toLocaleString()}) — AdultWorld.ai`,
    description: `Browse ${count.toLocaleString()} verified escorts offering ${serviceInfo.displayName} services on AdultWorld.ai. View profiles, photos, reviews, and book with confidence.`,
    openGraph: {
      title: `${serviceInfo.displayName} Escorts — AdultWorld.ai`,
      description: `Find ${count.toLocaleString()} escorts offering ${serviceInfo.displayName} on AdultWorld.ai.`,
    },
  };
}

export function generateStaticParams() {
  return validSlugs.map((service) => ({ service }));
}

// ISR — generateStaticParams + revalidate works; the prior `force-dynamic`
// override defeated static generation entirely.
export const revalidate = 600;

export default async function ServiceLandingPage({ params }: Props) {
  const { service } = await params;
  const serviceInfo = serviceMap[service];

  if (!serviceInfo) {
    notFound();
  }

  // Find the enjoy record
  const enjoy = await prisma.enjoy.findFirst({
    where: { name: serviceInfo.name },
  });

  if (!enjoy) {
    notFound();
  }

  // Get escorts who offer this service
  const enjoyUsers = await prisma.enjoyUser.findMany({
    where: {
      enjoy_id: enjoy.id,
      user: { user_type: "escort", active: true, banned_at: null },
    },
    include: {
      user: {
        include: {
          country: true,
          city: true,
          _count: { select: { photos: true } },
        },
      },
    },
    take: 48,
    orderBy: { user: { hits: "desc" } },
  });

  const escorts = await withAvatarUrls(enjoyUsers.map((eu) => eu.user));
  const totalCount = await prisma.enjoyUser.count({
    where: {
      enjoy_id: enjoy.id,
      user: { user_type: "escort", active: true },
    },
  });

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";
  const collectionLd = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: `${serviceInfo.displayName} Escorts`,
    url: `${baseUrl}/escorts/services/${service}`,
    mainEntity: {
      "@type": "ItemList",
      numberOfItems: escorts.length,
      itemListElement: escorts.map((u, idx) => ({
        "@type": "ListItem",
        position: idx + 1,
        url: `${baseUrl}/view/${u.id_aw ?? u.id}`,
        name: u.username ?? "",
      })),
    },
  };
  const breadcrumbsLd = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: baseUrl },
      { "@type": "ListItem", position: 2, name: "Escorts", item: `${baseUrl}/escorts` },
      { "@type": "ListItem", position: 3, name: serviceInfo.displayName, item: `${baseUrl}/escorts/services/${service}` },
    ],
  };

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(collectionLd) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbsLd) }} />
      {/* Hero */}
      <div className="text-center mb-12">
        <h1 className="text-4xl md:text-5xl font-bold text-gold mb-4 font-heading">
          {serviceInfo.displayName} Escorts
        </h1>
        <p className="text-text-muted text-sm mb-2">
          {totalCount.toLocaleString()} verified escorts offering{" "}
          {serviceInfo.displayName} services
        </p>
      </div>

      {/* Service Description */}
      <section className="mb-12">
        <div className="bg-surface rounded-2xl p-8 border border-surface-light max-w-4xl mx-auto">
          <h2 className="text-xl font-bold text-text mb-3">
            About {serviceInfo.displayName}
          </h2>
          <p className="text-text-muted text-sm leading-relaxed">
            {serviceInfo.description}
          </p>
        </div>
      </section>

      {/* Service Navigation */}
      <section className="mb-8">
        <div className="flex flex-wrap gap-2 justify-center">
          {validSlugs.map((slug) => (
            <Link
              key={slug}
              href={`/escorts/services/${slug}`}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                slug === service
                  ? "bg-gold text-black"
                  : "bg-surface border border-surface-light text-text-muted hover:border-gold/30 hover:text-gold"
              }`}
            >
              {serviceMap[slug].displayName}
            </Link>
          ))}
        </div>
      </section>

      {/* Escort Grid */}
      {escorts.length > 0 ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          {escorts.map((escort) => (
            <EscortCard key={escort.id} escort={escort} />
          ))}
        </div>
      ) : (
        <div className="text-center py-16 text-text-muted">
          <svg
            className="h-16 w-16 mx-auto mb-4 opacity-30"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
          <p className="text-lg font-medium mb-2">No escorts found</p>
          <p className="text-sm">
            No escorts currently list {serviceInfo.displayName} as a service.
            Check back soon or{" "}
            <Link href="/escorts" className="text-gold hover:text-gold/80">
              browse all escorts
            </Link>
            .
          </p>
        </div>
      )}

      {/* Load More Link */}
      {totalCount > 48 && (
        <div className="mt-8 text-center">
          <Link
            href={`/search/results?services=${enjoy.id}`}
            className="inline-flex items-center gap-2 text-gold hover:text-gold/80 font-medium transition-colors"
          >
            View all {totalCount.toLocaleString()} escorts offering{" "}
            {serviceInfo.displayName}
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 7l5 5m0 0l-5 5m5-5H6"
              />
            </svg>
          </Link>
        </div>
      )}

      {/* SEO Internal Links */}
      <section className="mt-16">
        <div className="bg-surface rounded-2xl p-8 border border-surface-light">
          <h2 className="text-lg font-bold text-text mb-4 text-center">
            Explore More Services
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {validSlugs
              .filter((slug) => slug !== service)
              .map((slug) => (
                <Link
                  key={slug}
                  href={`/escorts/services/${slug}`}
                  className="bg-background rounded-xl p-4 border border-surface-light hover:border-gold/30 transition-colors text-center"
                >
                  <span className="text-sm font-medium text-text hover:text-gold transition-colors">
                    {serviceMap[slug].displayName}
                  </span>
                </Link>
              ))}
          </div>
          <div className="mt-6 text-center">
            <Link
              href="/escorts"
              className="text-gold hover:text-gold/80 font-medium text-sm transition-colors"
            >
              Browse all escorts &rarr;
            </Link>
          </div>
        </div>
      </section>
    </div>
  );
}
