import { redirect } from 'next/navigation';

import { listOrders } from '~/medusa/lib/data/orders';
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { listProductTypes } from '@lib/data/products';
import { PageBody } from '@kit/ui/makerkit/page';
import pathsConfig from '~/config/paths.config';
import { Trans } from '@kit/ui/trans';
import { HomeLayoutPageHeader } from '../../_components/home-page-header';
import OrdersTable from '../../_components/orders/orders-table';
import { withI18n } from '~/lib/i18n/with-i18n';
import type { IOrderLineItem } from '../../_components/orders/types';

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

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

async function OrdersPage() {
  const orders = await listOrders().catch(() => null);
  const { productTypes } = await listProductTypes();

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

  const analysisPackagesType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages');
  const analysisPackageOrders: IOrderLineItem[] = orders.flatMap(({ id, items, payment_status, fulfillment_status }) => items
    ?.filter((item) => item.product_type_id === analysisPackagesType?.id)
    .map((item) => ({ item, orderId: id, orderStatus: `${payment_status}/${fulfillment_status}` }))
  || []);

  const otherOrders: IOrderLineItem[] = orders
    .filter(({ items }) => items?.some((item) => item.product_type_id !== analysisPackagesType?.id))
    .flatMap(({ id, items, payment_status, fulfillment_status }) => items
      ?.map((item) => ({ item, orderId: id, orderStatus: `${payment_status}/${fulfillment_status}` }))
    || []);

  return (
    <>
      <HomeLayoutPageHeader
        title={<Trans i18nKey={'orders:title'} />}
        description={<Trans i18nKey={'orders:description'} />}
      />
      <PageBody>
        <OrdersTable orderItems={analysisPackageOrders} title="orders:table.analysisPackage" />
        <OrdersTable orderItems={otherOrders} title="orders:table.otherOrders" />
      </PageBody>
    </>
  );
}

export default withI18n(OrdersPage);
