// productdetails/[slug]/page.tsx
// This is a Server Component - can be async

import ProductGallery from "../components/ProductGallery";
import ProductInfo from "../components/ProductInfo";
import RelatedProducts from "../components/RelatedProducts";
import NewsletterSection from "../components/NewsletterSection";
import ProductDetailsClient from "../components/ProductDetailsClient";
import Newsletter from "@/components/frontend-pages/home/Newsletter";
import { Metadata } from "next";

// API base URL - adjust based on your environment
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";

async function getProduct(slug: string) {
  try {
    const response = await fetch(`${API_BASE_URL}/clientapi/products/${slug}`, {
      cache: "no-store", // Don't cache - get fresh data
      // OR use: next: { revalidate: 3600 } for ISR
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch product: ${response.status}`);
    }

    const result = await response.json();

    if (!result.success) {
      throw new Error(result.error || "Failed to fetch product");
    }

    return result.data;
  } catch (error) {
    console.error("Error fetching product:", error);
    return null;
  }
}

// export const metadata: Metadata = {
//   title: "Products",
// };

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;

  const product = await getProduct(slug);

  return {
    title: product
      ? `Products | ${product.name}`
      : "Products",
  };
}

export default async function ProductDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  // Unwrap the params Promise by awaiting it
  const { slug } = await params;
  const product = await getProduct(slug);

  if (!product) {
    return (
      <div className="container mx-auto px-4 py-20 text-center">
        <h2 className="mb-4 text-2xl font-bold">Product Not Found</h2>
        <p className="mb-8 text-gray-600">
          The product you're looking for doesn't exist or has been removed.
        </p>
        <a href="/products" className="theme-btn">
          Browse Products
        </a>
      </div>
    );
  }

  // Transform API data to match component props
  const transformedProduct = {
    id: product._id,
    name: product.name,
    slug: product.slug,
    sku: product.sku || `${product._id.slice(-6)}`,
    price: product.price || product.minPrice || 0,
    originalPrice: product.productprice,
    category: product.category?.name || "Products",
    subcategory: product.subcategory?.name,
    description: product.description,
    shortDescription: product.shortDescription,
    images:
      product.variants
        ?.flatMap(
          (variant: any) => variant.images?.map((img: any) => img.url) || [],
        )
        .filter(Boolean) || [product.defaultImage].filter(Boolean),
    colors:
      product.variants?.map((variant: any) => ({
        id: variant._id,
        name: variant.name,
        code: variant.hexCode,
        images: variant.images || [],
      })) || [],
    sizes: [
      ...new Set(
        (product.variants ?? []).flatMap((variant: any) =>
          (variant.sizes ?? []).map((size: any) => size.name),
        ),
      ),
    ],
    variants: product.variants || [],
    reviews: product.reviews || [],
    minPrice: product.minPrice,
    maxPrice: product.maxPrice,
    hasSkus: product.hasSkus,
    weight: product.weight,
    dimensions: product.dimensions,
    isActive: product.isActive,
    isFeatured: product.isFeatured,
    defaultImage: product.defaultImage,
  };

  return (
    <div>
      <Breadcrumb product={transformedProduct} />
      <section className="productdlcontainer">
        <div className="container px-3">
          <ProductDetailsClient product={transformedProduct} />
        </div>
      </section>
      <RelatedProducts
        currentProductId={product._id}
        category={product.category?.slug}
      />
      <div className="blogbtmimg">
        <img src="images/blog-btm-img.png" alt="" />
      </div>
      <Newsletter />
    </div>
  );
}

// Breadcrumb Component
function Breadcrumb({ product }: { product: any }) {
  const categorySlug =
    product.category?.trim().toLowerCase().replace(/\s+/g, "-") || "";
  return (
    <section className="breadcrumbcontainer">
      <div className="container px-3">
        <div className="row">
          <div className="col-12">
            <ol className="breadcrumb">
              <li>
                <a href="/">Home</a>
              </li>
              <li>
                <a href="/products">Products</a>
              </li>
              <li>
                <a href={`/products?category=${categorySlug}`}>
                  {product.category || "Products"}
                </a>
              </li>
              <li className="active">{product.name}</li>
            </ol>
          </div>
        </div>
      </div>
    </section>
  );
}
