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

export const revalidate = 600;

interface Props {
  params: Promise<{ countrySlug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { countrySlug } = await params;
  const country = await prisma.country.findFirst({
    where: { slug: countrySlug, active: true },
  });
  if (!country) return {};
  return {
    title: `Escorts in ${country.name} - Browse Verified Companions | AdultWorld`,
    description: `Find verified escorts and companions in ${country.name}. Browse profiles, read reviews, and connect with top-rated providers across all cities in ${country.name}.`,
    openGraph: {
      title: `Escorts in ${country.name} | AdultWorld`,
      description: `Browse verified escorts in ${country.name}. Find companions in major cities across the country.`,
    },
  };
}

export default async function CountryLandingPage({ params }: Props) {
  const { countrySlug } = await params;

  const country = await prisma.country.findFirst({
    where: { slug: countrySlug, active: true },
    include: {
      cities: {
        orderBy: { name: "asc" },
        include: {
          _count: {
            select: {
              users: { where: { user_type: "escort" } },
            },
          },
        },
      },
    },
  });

  if (!country) notFound();

  // Fetch top_text from country if it exists
  let topText: string | null = null;
  try {
    const result: { top_text: string | null }[] = await prisma.$queryRawUnsafe(
      `SELECT top_text FROM countries WHERE id = $1 LIMIT 1`,
      country.id
    );
    topText = result[0]?.top_text ?? null;
  } catch {
    // top_text column may not exist
  }

  const escortWhere = {
    user_type: "escort" as const,
    country_id: country.id,
    active: true,
    banned_at: null,
  };

  const [escorts, totalCount] = await Promise.all([
    prisma.user.findMany({
      where: escortWhere,
      include: { country: true, city: true },
      orderBy: [{ is_vip: "desc" }, { is_verified: "desc" }, { hits: "desc" }],
      take: 12,
    }),
    prisma.user.count({ where: escortWhere }),
  ]);
  const escortsWithAvatars = await withAvatarUrls(escorts);

  const citiesWithEscorts = country.cities.filter((c) => c._count.users > 0);

  return (
    <div className="space-y-10">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-text-muted">
        <Link href="/" className="hover:text-white transition-colors">Home</Link>
        <span>/</span>
        <Link href="/escorts" className="hover:text-white transition-colors">Escorts</Link>
        <span>/</span>
        <span className="text-white">{country.name}</span>
      </div>

      {/* Hero */}
      <section className="relative text-center py-12 md:py-16">
        <div className="absolute inset-0 bg-gradient-to-b from-primary/5 via-transparent to-transparent rounded-2xl" />
        <div className="relative">
          <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold mb-4">
            Escorts in <span className="text-primary">{country.name}</span>
          </h1>
          <p className="text-text-muted text-lg max-w-2xl mx-auto">
            Browse {totalCount.toLocaleString()} verified escorts across {citiesWithEscorts.length} cities in {country.name}.
          </p>
        </div>
      </section>

      {/* Country description */}
      {topText && (
        <section className="bg-surface rounded-xl border border-white/5 p-6">
          <div
            className="prose prose-invert prose-sm max-w-none text-text-muted"
            dangerouslySetInnerHTML={{ __html: topText }}
          />
        </section>
      )}

      {/* Stats bar */}
      <section className="grid grid-cols-3 gap-4">
        <div className="bg-surface rounded-xl border border-white/5 p-5 text-center">
          <p className="text-2xl font-bold text-primary">{totalCount.toLocaleString()}</p>
          <p className="text-xs text-text-muted mt-1">Active Escorts</p>
        </div>
        <div className="bg-surface rounded-xl border border-white/5 p-5 text-center">
          <p className="text-2xl font-bold text-primary">{citiesWithEscorts.length}</p>
          <p className="text-xs text-text-muted mt-1">Cities</p>
        </div>
        <div className="bg-surface rounded-xl border border-white/5 p-5 text-center">
          <p className="text-2xl font-bold text-primary">
            {escorts.filter((e) => e.is_verified).length}
          </p>
          <p className="text-xs text-text-muted mt-1">Verified Profiles</p>
        </div>
      </section>

      {/* City Links Grid */}
      {citiesWithEscorts.length > 0 && (
        <section>
          <h2 className="text-xl md:text-2xl font-bold mb-5">
            Cities in {country.name}
          </h2>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
            {citiesWithEscorts.map((city) => (
              <Link
                key={city.id}
                href={`/escorts/${countrySlug}/${city.slug}`}
                className="group bg-surface border border-white/5 rounded-xl p-4 transition-all duration-200 hover:border-primary/30 hover:bg-surface-light"
              >
                <h3 className="font-semibold text-white group-hover:text-primary transition-colors text-sm truncate">
                  {city.name}
                </h3>
                <p className="text-xs text-text-muted mt-1">
                  {city._count.users} {city._count.users === 1 ? "escort" : "escorts"}
                </p>
              </Link>
            ))}
          </div>
        </section>
      )}

      {/* Top Escorts */}
      {escorts.length > 0 && (
        <section>
          <div className="flex items-center justify-between mb-5">
            <h2 className="text-xl md:text-2xl font-bold">
              Top Escorts in {country.name}
            </h2>
            <Link
              href={`/escorts/${countrySlug}`}
              className="text-sm text-primary hover:text-primary-light transition-colors font-medium"
            >
              View All
            </Link>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
            {escortsWithAvatars.map((escort) => (
              <EscortCard key={escort.id} escort={escort} />
            ))}
          </div>
        </section>
      )}

      {/* SEO Content */}
      <section className="bg-surface rounded-xl border border-white/5 p-6">
        <h2 className="text-lg font-semibold mb-3">About Escorts in {country.name}</h2>
        <p className="text-text-muted text-sm leading-relaxed">
          AdultWorld features {totalCount.toLocaleString()} verified escort profiles in {country.name}.
          Browse companions across {citiesWithEscorts.length} cities, read genuine reviews, and connect
          securely through our messaging system. All profiles are verified for your safety and peace of mind.
        </p>
      </section>
    </div>
  );
}
