import { notFound } from 'next/navigation';

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

import { Trans } from '@kit/ui/trans';

import { withI18n } from '~/lib/i18n/with-i18n';
import { getCartReservations } from '~/lib/services/reservation.service';
import { findProductTypeIdByHandle } from '~/lib/utils';

import Cart from '../../_components/cart';
import CartTimer from '../../_components/cart/cart-timer';
import { EnrichedCartItem } from '../../_components/cart/types';

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

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

async function CartPage() {
  const cart = await retrieveCart().catch((error) => {
    console.error('Failed to retrieve cart', error);
    return notFound();
  });

  const { productTypes } = await listProductTypes();

  const synlabAnalysisTypeId = findProductTypeIdByHandle(
    productTypes,
    'synlab-analysis',
  );
  const analysisPackagesTypeId = findProductTypeIdByHandle(
    productTypes,
    'analysis-packages',
  );

  const synlabAnalyses =
    analysisPackagesTypeId && synlabAnalysisTypeId && cart?.items
      ? cart.items.filter((item) => {
          const productTypeId = item.product?.type_id;
          if (!productTypeId) {
            return false;
          }
          return [analysisPackagesTypeId, synlabAnalysisTypeId].includes(
            productTypeId,
          );
        })
      : [];

  let ttoServiceItems: EnrichedCartItem[] = [];
  if (cart?.items?.length) {
    ttoServiceItems = await getCartReservations(cart);
  }
  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>
  );
}

export default withI18n(CartPage);
