import React from "react";
import type { Metadata, ResolvingMetadata } from "next";
import { getPropertyBySlug } from "@/services/propertyService";
import PropertyDetailClient from "./PropertyDetailClient";

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

/**
 * Dynamic Open Graph & Twitter Card Metadata Generator
 * When a property link is shared/pasted on WhatsApp, Facebook, LinkedIn, Twitter/X,
 * this returns the property's hero thumbnail, title, price, and specifications.
 */
export async function generateMetadata(
  { params }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const resolvedParams = await params;
  const property = await getPropertyBySlug(resolvedParams.id);

  if (!property) {
    return {
      title: "Luxury Property | DreamHomes Sri Lanka",
      description: "Explore premier residential and commercial real estate across Sri Lanka.",
    };
  }

  const priceText = property.priceDisplayLKR || (property.priceLKR ? `LKR ${property.priceLKR} Million` : "Price on Request");
  const locationText = property.location || property.address || "Sri Lanka";
  const bedrooms = property.bedrooms ? `${property.bedrooms} Beds` : "";
  const bathrooms = property.bathrooms ? `${property.bathrooms} Baths` : "";
  const sqft = property.sqft ? `${Number(property.sqft).toLocaleString()} SqFt` : "";
  
  const specs = [bedrooms, bathrooms, sqft, locationText].filter(Boolean).join(" • ");

  const title = `${property.title} - ${priceText} | DreamHomes`;
  const description = `${priceText} | ${specs}. ${property.description ? property.description.slice(0, 160) : "Exclusive luxury residence with premium architectural finishes and verified title deed."}`;

  const heroImage = property.heroImage || "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1200&q=85";
  const canonicalUrl = `https://dreamhomes.lk/properties/${property.slug || resolvedParams.id}`;

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      url: canonicalUrl,
      siteName: "DreamHomes Real Estate",
      type: "article",
      images: [
        {
          url: heroImage,
          width: 1200,
          height: 630,
          alt: property.title,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [heroImage],
      creator: "@DreamHomesLK",
    },
    alternates: {
      canonical: canonicalUrl,
    },
  };
}

export default async function PropertyPage({ params }: Props) {
  const resolvedParams = await params;
  const property = await getPropertyBySlug(resolvedParams.id);

  return (
    <PropertyDetailClient
      id={resolvedParams.id}
      initialProperty={property}
    />
  );
}
