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 { AccountBalanceService } from '@kit/accounts/services/account-balance.service';
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';
import { loadCurrentUserAccount } from '../../_lib/server/load-user-account';

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

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

async function CartPage() {
  const [cart, { productTypes }, { account }] = await Promise.all([
    retrieveCart(),
    listProductTypes(),
    loadCurrentUserAccount(),
  ]);

  if (!account) {
    return null;
  }

  const balanceSummary = await new AccountBalanceService().getBalanceSummary(
    account.id,
  );

  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
        accountId={account.id}
        cart={cart}
        synlabAnalyses={synlabAnalyses}
        ttoServiceItems={ttoServiceItems}
        balanceSummary={balanceSummary}
      />
    </PageBody>
  );
}

export default withI18n(CartPage);
