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';

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

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

async function OrdersPage() {
  const medusaOrders = await listOrders();
  const analysisOrders = await getAnalysisOrders();
  const ttoOrders = await getTtoOrders();
  const { productTypes } = await 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) => {
          const analysisOrder = analysisOrders.find(
            ({ medusa_order_id }) => medusa_order_id === medusaOrder.id,
          );
          if (!medusaOrder) {
            return null;
          }

          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}
                itemsAnalysisPackage={medusaOrderItemsAnalysisPackages}
                itemsTtoService={medusaOrderItemsTtoServices}
                itemsOther={medusaOrderItemsOther}
              />
            </React.Fragment>
          );
        })}
        {analysisOrders.length === 0 && (
          <h5 className="mt-6">
            <Trans i18nKey="orders:noOrders" />
          </h5>
        )}
      </PageBody>
    </>
  );
}

export default withI18n(OrdersPage);
