import { getImageUrl } from "@/utils/imageHelper";
import { APPLE_ICON, OG_BANNER } from "@/utils/staticValues";
import { Metadata } from "next";
import { serverApiClient } from "@/utils/serverApiClient";
import ProductView from "./ProductView";

// Helper function to fetch product data directly from external API
async function fetchProductData(productId: string) {
  const result = await serverApiClient(`product/${productId}`, {
    method: 'GET',
    revalidate: 300, // Cache for 5 minutes
  });

  if (!result.success || !result.data) {
    throw new Error(`Failed to fetch product data`);
  }
  
  return result.data;
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ productId: string }>;
}): Promise<Metadata> {
  const { productId } = await params;
  
  try {
    const data = await fetchProductData(productId);
    const product = data?.product;

    if (!product) {
      return {
        title: "Product Not Found | Morni",
        description: "The requested product could not be found.",
      };
    }

    // Get the primary image for social sharing
    const primaryImage = product.main_item_images?.[0]?.image_url || 
                        product.main_item_image?.image_url;
    
    // Use getImageUrl to ensure the image URL is properly formatted
    const socialShareImage = primaryImage ? getImageUrl(primaryImage) : OG_BANNER;

    // Create SEO-friendly title and description
    const productSeoTitle = `${product.product_name} - ${product.category?.name || 'Fashion'} | Morni`;
    const productDescription = `Shop ${product.product_name} for $${product.price}. ${product.category?.name ? `Browse our ${product.category.name} collection` : 'Discover unique fashion pieces'} at Morni.`;

    return {
      title: productSeoTitle,
      description: productDescription,
      openGraph: {
        title: productSeoTitle,
        description: productDescription,
        images: [
          {
            url: socialShareImage,
            width: 1200,
            height: 630,
            alt: product.product_name,
          },
        ],
        type: 'website',
        siteName: 'Morni',
      },
      twitter: {
        card: "summary_large_image",
        title: productSeoTitle,
        description: productDescription,
        images: [socialShareImage],
      },
      icons: {
        apple: APPLE_ICON,
      },
      appleWebApp: {
        capable: true,
        statusBarStyle: "default",
        title: productSeoTitle
      },
      keywords: [
        product.product_name,
        product.category?.name,
        product.sub_category?.name,
        product.design_house?.name,
        'fashion',
        'clothing',
        'morni'
      ].filter(Boolean).join(', '),
      alternates: {
        canonical: `https://mymorni.com/product/${productId}`,
      },
    };
  } catch (error) {
    console.error("Error generating metadata:", error);
    return {
      title: "Product | Morni",
      description: "Discover unique fashion pieces at Morni.",
    };
  }
}

export default async function ProductDetailPage({
  params,
}: {
  params: Promise<{ productId: string }>;
}) {
  const { productId } = await params;

  try {
    const data = await fetchProductData(productId);
    
    return <ProductView data={data} />;
  } catch (error) {
    console.error("Error fetching product:", error);
    
    return (
      <div className="wrapper py-20 text-center">
        <h1 className="text-2xl font-bold">Product not found</h1>
        <p className="mt-4">Sorry, we couldn&apos;t load this product.</p>
      </div>
    );
  }
}
