import React from 'react';

import { redirect } from 'next/navigation';

import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { listProductTypes } from '@lib/data/products';
import { Divider } from '@medusajs/ui';

import { pathsConfig } from '@kit/shared/config';
import { PageBody } from '@kit/ui/makerkit/page';
import { Trans } from '@kit/ui/trans';

import { withI18n } from '~/lib/i18n/with-i18n';
import { getAnalysisOrders, getTtoOrders } from '~/lib/services/order.service';
import { findProductTypeIdByHandle } from '~/lib/utils';
import { listOrders } from '~/medusa/lib/data/orders';

import { HomeLayoutPageHeader } from '../../_components/home-page-header';
import OrderBlock from '../../_components/orders/order-block';

const ORDERS_LIMIT = 50;

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

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

async function OrdersPage() {
  const [medusaOrders, analysisOrders, ttoOrders, { productTypes }] =
    await Promise.all([
      listOrders(ORDERS_LIMIT),
      getAnalysisOrders(),
      getTtoOrders(),
      listProductTypes(),
    ]);

  if (!medusaOrders || !productTypes || !ttoOrders) {
    redirect(pathsConfig.auth.signIn);
  }

  const analysisPackagesTypeId = findProductTypeIdByHandle(
    productTypes,
    'analysis-package',
  );
  const ttoServiceTypeId = findProductTypeIdByHandle(
    productTypes,
    'tto-service',
  );

  return (
    <>
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'orders:title'} />}
        description={<Trans i18nKey={'orders:description'} />}
      />
      <PageBody>
        {medusaOrders.map((medusaOrder) => {
          if (!medusaOrder) {
            return null;
          }

          const analysisOrder = analysisOrders.find(
            ({ medusa_order_id }) => medusa_order_id === medusaOrder.id,
          );

          const ttoReservation = ttoOrders.find(({ id }) => {
            const connectedOnlineReservationId =
              medusaOrder?.items &&
              medusaOrder.items.find(
                ({ metadata }) => !!metadata?.connectedOnlineReservationId,
              )?.metadata?.connectedOnlineReservationId;
            return id === connectedOnlineReservationId;
          });

          const medusaOrderItems = medusaOrder.items || [];
          const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
            (item) => item.product_type_id === analysisPackagesTypeId,
          );
          const medusaOrderItemsTtoServices = medusaOrderItems.filter(
            (item) => item.product_type_id === ttoServiceTypeId,
          );
          const medusaOrderItemsOther = medusaOrderItems.filter(
            (item) =>
              !item.product_type_id ||
              ![analysisPackagesTypeId, ttoServiceTypeId].includes(
                item.product_type_id,
              ),
          );

          return (
            <React.Fragment key={medusaOrder.id}>
              <Divider className="my-6" />
              <OrderBlock
                medusaOrderId={medusaOrder.id}
                analysisOrder={analysisOrder}
                ttoReservation={ttoReservation}
                medusaOrderStatus={medusaOrder.status}
                itemsAnalysisPackage={medusaOrderItemsAnalysisPackages}
                itemsTtoService={medusaOrderItemsTtoServices}
                itemsOther={medusaOrderItemsOther}
              />
            </React.Fragment>
          );
        })}
        {analysisOrders.length === 0 && ttoOrders.length === 0 && (
          <h5 className="mt-6">
            <Trans i18nKey="orders:noOrders" />
          </h5>
        )}
      </PageBody>
    </>
  );
}

export default withI18n(OrdersPage);
