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 } from '~/lib/services/order.service';
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, { productTypes }] = await Promise.all([
    listOrders(ORDERS_LIMIT),
    getAnalysisOrders(),
    listProductTypes(),
  ]);

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

  const analysisPackagesType = productTypes.find(
    ({ metadata }) => metadata?.handle === 'analysis-packages',
  )!;

  return (
    <>
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'orders:title'} />}
        description={<Trans i18nKey={'orders:description'} />}
      />
      <PageBody>
        {analysisOrders.map((analysisOrder) => {
          const medusaOrder = medusaOrders.find(
            ({ id }) => id === analysisOrder.medusa_order_id,
          );
          if (!medusaOrder) {
            return null;
          }

          const medusaOrderItems = medusaOrder.items || [];
          const medusaOrderItemsAnalysisPackages = medusaOrderItems.filter(
            (item) => item.product_type_id === analysisPackagesType?.id,
          );
          const medusaOrderItemsOther = medusaOrderItems.filter(
            (item) => item.product_type_id !== analysisPackagesType?.id,
          );

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

export default withI18n(OrdersPage);
