import { redirect } from 'next/navigation';

import CartTotals from '@/app/home/(user)/_components/order/cart-totals';
import OrderDetails from '@/app/home/(user)/_components/order/order-details';
import OrderItems from '@/app/home/(user)/_components/order/order-items';
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { getSupabaseServerClient } from '@/packages/supabase/src/clients/server-client';
import { retrieveOrder } from '@lib/data/orders';
import Divider from '@modules/common/components/divider';

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

import { withI18n } from '~/lib/i18n/with-i18n';

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

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

async function OrderConfirmedPage(props: {
  params: Promise<{ orderId: string }>;
}) {
  const supabaseClient = getSupabaseServerClient();
  const params = await props.params;
  const medusaOrder = await retrieveOrder(params.orderId).catch(() => null);
  if (!medusaOrder) {
    redirect(pathsConfig.app.myOrders);
  }
  const ttoReservationId =
    medusaOrder.items &&
    (medusaOrder.items.find(
      ({ metadata }) => !!metadata?.connectedOnlineReservationId,
    )?.metadata?.connectedOnlineReservationId as number);

  const [{ data: ttoReservation }] = await Promise.all([
    ttoReservationId
      ? await supabaseClient
          .schema('medreport')
          .from('connected_online_reservation')
          .select('*')
          .eq('id', ttoReservationId)
          .single()
      : { data: null },
  ]);
  const [{ data: location }, { data: serviceProvider }] = await Promise.all([
    supabaseClient
      .schema('medreport')
      .from('connected_online_locations')
      .select('name,address')
      .eq('sync_id', ttoReservation.location_sync_id || 0)
      .single(),
    supabaseClient
      .schema('medreport')
      .from('connected_online_providers')
      .select('email,phone_number,name')
      .eq('id', ttoReservation.clinic_id)
      .single(),
  ]);

  return (
    <PageBody>
      <PageHeader title={<Trans i18nKey="cart:order.title" />} />
      <Divider />
      <div className="small:grid-cols-[1fr_360px] grid grid-cols-1 gap-x-40 gap-y-6 lg:px-4">
        <OrderDetails
          order={{
            id: medusaOrder.id,
            created_at: medusaOrder.created_at,
            location,
            serviceProvider,
          }}
        />
        <Divider />
        <OrderItems medusaOrder={medusaOrder} />
        <CartTotals medusaOrder={medusaOrder} />
      </div>
    </PageBody>
  );
}

export default withI18n(OrderConfirmedPage);
