import { notFound } from "next/navigation";
import { Metadata } from "next";

import ProductPageStatus from "@/features/product/product-page-status";
import PageWrapper from "@/components/page-wrapper";

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

export async function generateMetadata({
  params,
}: ProductDetailsPageProps): Promise<Metadata> {
  const { id, locale } = await params;

  try {
    // Use the same API proxy that ProductPageStatus uses
    const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || `http://localhost:${process.env.PORT || 3000}`;
    const res = await fetch(
      `${baseUrl}/api/catalog/productdetails?productId=${id}&locale=${locale}`,
      { method: "GET", next: { revalidate: 60 } }
    );

    if (!res.ok) throw new Error("Product not found");

    const result = await res.json();
    // The proxy returns { data: markattyResponse }
    // Try multiple paths to find product details
    const raw = result?.data;
    const productName = raw?.name || raw?.data?.name || raw?.product?.name || "منتج";
    const productDesc = raw?.shortDescription || raw?.data?.description || raw?.description || "";
    const productImage = raw?.thumbNail || raw?.data?.base_image?.original_image_url || raw?.images?.[0]?.url || "/assets/images/no-image.webp";

    return {
      title: `${productName} | بالمي`,
      description: productDesc || "اكتشف هذا المنتج المميز!",
      openGraph: {
        title: productName,
        description: productDesc || "اكتشف هذا المنتج المميز!",
        url: `${process.env.NEXT_PUBLIC_SITE_URL}/${locale}/product/${id}`,
        images: [
          {
            url: productImage,
            width: 1200,
            height: 630,
            alt: productName,
          },
        ],
        siteName: "بالمي",
        type: "website",
      },
      twitter: {
        card: "summary_large_image",
        title: productName,
        description: productDesc || "اكتشف هذا المنتج المميز!",
        images: [productImage],
      },
    };
  } catch {
    return {
      title: "Product not found",
      description: "The requested product could not be found.",
      openGraph: {
        title: "Product not found",
        description: "The requested product could not be found.",
        url: `${process.env.NEXT_PUBLIC_SITE_URL}/${locale}/product/${id}`,
      },
      twitter: {
        card: "summary_large_image",
        title: "Product not found",
        description: "The requested product could not be found.",
      },
    };
  }
}

export default async function ProductDetailsPage({
  params,
}: ProductDetailsPageProps) {
  const { id, locale } = await params;
  const productId = parseInt(id);
  if (isNaN(productId)) notFound();

  return (
    <PageWrapper>
      <ProductPageStatus productId={productId} locale={locale} />
    </PageWrapper>
  );
}
