import ProductLayout from '@theme/views/product/layout';
import { ProductGroupInfo } from '@theme/views/product';
import { getProductData, getWidgetData } from '@akinon/next/data/server';
import { withSegmentDefaults } from '@akinon/next/hocs/server';
import { AsyncPageProps, ResolvedPageProps, Metadata } from '@akinon/next/types';
import { generateJsonLd, serializeJsonLd } from '@theme/utils/generate-jsonld';
import { notFound } from 'next/navigation';

export async function generateMetadata(
  props: AsyncPageProps<{ pk: number }>
) {
  const params = await props.params;
  const searchParams = await props.searchParams;
  let result: Metadata = {};

  try {
    const { data } = await getProductData({
      pk: params.pk,
      searchParams,
      groupProduct: true
    });

    const product = data?.product;

    if (!product) {
      return {};
    }

    result = {
      title: product.name,
      description: String(product.attributes?.description),
      twitter: {
        title: product.name,
        description: String(product.attributes?.description)
      },
      openGraph: {
        title: product.name,
        description: String(product.attributes?.description),
        images: product.productimage_set?.map((item) => ({
          url: item.image
        }))
      }
    };
  } catch (error: unknown) {
    if ((error as Error & { status?: number })?.status === 404) {
      notFound();
    }
    throw error;
  }

  return result;
}

async function Page({ params, searchParams }: ResolvedPageProps<{ pk: number }>) {
  if (params.pk === undefined || isNaN(Number(params.pk))) {
    notFound();
  }

  try {
    const [{ data, breadcrumbData }, deliveryReturn] = await Promise.all([
      getProductData({
        pk: params.pk,
        searchParams,
        groupProduct: true
      }),
      getWidgetData({ slug: 'product-delivery-returns' })
    ]);

    const jsonLd = generateJsonLd(data.product);

    return (
      <>
        <ProductLayout data={data} breadcrumbData={breadcrumbData}>
          <ProductGroupInfo
            data={data}
            deliveryReturn={deliveryReturn?.attributes}
          />
        </ProductLayout>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: serializeJsonLd(jsonLd) }}
        />
      </>
    );
  } catch (error: unknown) {
    if ((error as Error & { status?: number })?.status === 404) {
      notFound();
    }
    throw error;
  }
}

export default withSegmentDefaults(Page, { segmentType: 'page' });
