import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';

import { notFound } from 'next/navigation';

import { retrieveCart } from '@lib/data/cart';
import Cart from '../../_components/cart';
import { listProductTypes } from '@lib/data/products';
import CartTimer from '../../_components/cart/cart-timer';
import { Trans } from '@kit/ui/trans';

export async function generateMetadata() {
  const { t } = await createI18nServerInstance();

  return {
    title: t('cart:title'),
  };
}

export default async function CartPage() {
  const cart = await retrieveCart().catch((error) => {
    console.error(error);
    return notFound();
  });

  const { productTypes } = await listProductTypes();
  const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages');
  const synlabAnalysisType = productTypes.find(({ metadata }) => metadata?.handle === 'synlab-analysis');
  const synlabAnalyses = analysisPackagesType && synlabAnalysisType && cart?.items
    ? cart.items.filter((item) => {
        const productTypeId = item.product?.type_id;
        if (!productTypeId) {
          return false;
        }
        return [analysisPackagesType.id, synlabAnalysisType.id].includes(productTypeId);
      })
    : [];
  const ttoServiceItems = cart?.items?.filter((item) => !synlabAnalyses.some((analysis) => analysis.id === item.id)) ?? [];

  const otherItemsSorted = ttoServiceItems.sort((a, b) => (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 1);
  const item = otherItemsSorted[0];
  const isTimerShown = ttoServiceItems.length > 0 && !!item && !!item.updated_at;

  return (
    <PageBody>
      <PageHeader title={<Trans i18nKey="cart:title" />}>
        {isTimerShown && <CartTimer cartItem={item} />}
      </PageHeader>
      <Cart cart={cart} synlabAnalyses={synlabAnalyses} ttoServiceItems={ttoServiceItems} />
    </PageBody>
  );
}
