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';
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 analysisPackages = analysisPackagesType && cart?.items
    ? cart.items.filter((item) => item.product?.type_id === analysisPackagesType.id)
    : [];
  const otherItems = cart?.items?.filter((item) => item.product?.type_id !== analysisPackagesType?.id) ?? [];

  const otherItemsSorted = otherItems.sort((a, b) => (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 1);
  const item = otherItemsSorted[0];

  return (
    <PageBody>
      <PageHeader title={<Trans i18nKey="cart:title" />}>
        {item && item.updated_at && <CartTimer cartItem={item} />}
      </PageHeader>
      <Cart cart={cart} analysisPackages={analysisPackages} otherItems={otherItems} />
    </PageBody>
  );
}
