import fetchData from "@/api/fetch-data";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import DetailsRedesignThree from "@/app/ui/shared/SingleProductRedesignThree/DetailsRedesignThree";
import ProductDetailsTabRedesignThree from "@/app/ui/shared/SingleProductRedesignThree/ProductDetailsTabRedesignThree";
import RelativeProductsRedesignThree from "@/app/ui/shared/SingleProductRedesignThree/RelativeProductsRedesignThree";

async function fetchProductDetails(id) {
  return fetchData({
    endPoint: `/product/details/${id}`,
  });
}

export async function generateMetadata({ params }) {
  const id = params.id;
  try {
    const { data } = await fetchProductDetails(id);
    const metaTags = data?.meta_tags;
    return {
      title: metaTags?.title,
      description: metaTags?.description,
    };
  } catch (error) {}
}

export default async function ProductDetails({ params: { id } }) {
  // Fetch all data concurrently using Promise.all
  const [
    { data, message, error },
    { data: customFormInputs },
    { data: videoData },
  ] = await Promise.all([
    fetchProductDetails(id),
    fetchData({
      endPoint: `/user/products/custom-fields/${id}`,
    }),
    fetchData({
      endPoint: `/user/products/videos/${id}`,
    }),
  ]);

  if (error) {
    return <AlertWarning text={message} />;
  }

  const photos = [...data?.product?.photos];
  if (data?.features?.length > 0) {
    photos.push(...data?.features?.[0]?.images);
  }
  const relativeProducts = data?.similar || [];

  return (
    <div>
      {/* braedcrumb */}
      <CustomBreadcrumb route={data?.product?.title} subs={true} />
      {/* content */}
      <div className="container my-8 space-y-6">
        {/* product details */}
        <div className="container">
          {/* details */}
          <DetailsRedesignThree
            data={data}
            customFormInputs={customFormInputs}
            images={photos}
            videoUrl={videoData?.[0]?.video || null}
          />
          {/* images */}
        </div>
        {/* tabs */}
        {/* <ProductDetailsTabRedesign product={data?.product} /> */}
        <ProductDetailsTabRedesignThree data={data} />
        {/* relative products */}
        {relativeProducts.length > 0 ? (
          <RelativeProductsRedesignThree products={relativeProducts} />
        ) : null}
      </div>
    </div>
  );
}
