import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { ListingDetailClient } from '@/components/listings/listing-detail-client';
import {
  JsonLd,
  generateBreadcrumbJsonLd,
  generateListingJsonLd,
} from '@/components/seo/json-ld';
import { formatPrice } from '@/lib/currency';
import { fetchListingById } from '@/lib/listings-server';
import { PROPERTY_TYPES, TRANSACTION_TYPES } from '@/lib/validations/listings';

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn';

function getLabel(list: readonly { value: string; label: string }[], value: string | null) {
  if (!value) return null;
  return list.find((item) => item.value === value)?.label ?? value;
}

// ---------------------------------------------------------------------------
// Metadata (runs server-side, provides <title>, <meta>, OG, canonical)
// ---------------------------------------------------------------------------

interface PageProps {
  params: Promise<{ locale: string; id: string }>;
}

export async function generateMetadata({ params: paramsPromise }: PageProps): Promise<Metadata> {
  const params = await paramsPromise;
  const listing = await fetchListingById(params.id);
  if (!listing) {
    return { title: 'Kh\u00f4ng t\u00ecm th\u1ea5y tin \u0111\u0103ng' };
  }

  const { property } = listing;
  const propertyTypeLabel = getLabel(PROPERTY_TYPES, property.propertyType);
  const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType);
  const priceStr = formatPrice(listing.priceVND);
  const fullAddress = [property.address, property.ward, property.district, property.city]
    .filter(Boolean)
    .join(', ');

  const title = `${property.title} - ${priceStr} VND`;
  const description = [
    transactionLabel,
    propertyTypeLabel,
    `${property.areaM2} m\u00b2`,
    property.bedrooms != null ? `${property.bedrooms} PN` : null,
    fullAddress,
    `Gi\u00e1: ${priceStr} VND`,
  ]
    .filter(Boolean)
    .join(' | ');

  const canonicalUrl = `${siteUrl}/${params.locale}/listings/${params.id}`;
  const firstImage = property.media.find((m) => m.type === 'image');

  return {
    title,
    description,
    alternates: {
      canonical: canonicalUrl,
      languages: {
        vi: `${siteUrl}/vi/listings/${params.id}`,
        en: `${siteUrl}/en/listings/${params.id}`,
      },
    },
    openGraph: {
      type: 'article',
      locale: params.locale === 'vi' ? 'vi_VN' : 'en_US',
      url: canonicalUrl,
      title,
      description,
      siteName: 'GoodGo',
      images: firstImage
        ? [{ url: firstImage.url, width: 1200, height: 630, alt: property.title }]
        : [{ url: '/og-image.png', width: 1200, height: 630, alt: 'GoodGo' }],
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: firstImage ? [firstImage.url] : ['/og-image.png'],
    },
    other: {
      'og:price:amount': listing.priceVND,
      'og:price:currency': 'VND',
    },
  };
}

// ---------------------------------------------------------------------------
// Page (Server Component)
// ---------------------------------------------------------------------------

export default async function PublicListingDetailPage({ params: paramsPromise }: PageProps) {
  const params = await paramsPromise;
  const listing = await fetchListingById(params.id);

  if (!listing) {
    notFound();
  }

  const { property } = listing;

  // Build JSON-LD structured data
  const listingJsonLd = generateListingJsonLd(listing, siteUrl);
  const breadcrumbJsonLd = generateBreadcrumbJsonLd([
    { name: 'Trang ch\u1ee7', url: siteUrl },
    { name: 'T\u00ecm ki\u1ebfm', url: `${siteUrl}/search` },
    { name: property.title, url: `${siteUrl}/${params.locale}/listings/${params.id}` },
  ]);

  return (
    <>
      {/* Structured data for search engines */}
      <JsonLd data={listingJsonLd} />
      <JsonLd data={breadcrumbJsonLd} />

      {/* Interactive client component */}
      <ListingDetailClient listing={listing} />
    </>
  );
}
