'use client';

import { useEffect, useRef, useState } from 'react';

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 { retrieveOrder } from '@lib/data/orders';
import { StoreOrder } from '@medusajs/types';
import Divider from '@modules/common/components/divider';

import { GlobalLoader } from '@kit/ui/makerkit/global-loader';
import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';

import { AnalysisOrder } from '~/lib/types/analysis-order';

function OrderConfirmedLoadingWrapper({
  medusaOrder: initialMedusaOrder,
  order,
}: {
  medusaOrder: StoreOrder;
  order: AnalysisOrder;
}) {
  const [medusaOrder, setMedusaOrder] =
    useState<StoreOrder>(initialMedusaOrder);
  const fetchingRef = useRef(false);

  const paymentStatus = medusaOrder.payment_status;
  const medusaOrderId = order.medusa_order_id;

  useEffect(() => {
    if (paymentStatus === 'captured') {
      return;
    }

    const interval = setInterval(async () => {
      if (fetchingRef.current) {
        return;
      }

      fetchingRef.current = true;
      const medusaOrder = await retrieveOrder(medusaOrderId, false);
      fetchingRef.current = false;

      setMedusaOrder(medusaOrder);
    }, 2_000);

    return () => clearInterval(interval);
  }, [paymentStatus, medusaOrderId]);

  const isPaid = paymentStatus === 'captured';

  if (!isPaid) {
    return (
      <PageBody>
        <div className="flex h-full flex-col items-center justify-start pt-[10vh]">
          <div>
            <GlobalLoader />
          </div>
          <h4 className="text-center">
            <Trans i18nKey="cart:orderConfirmed.paymentConfirmationLoading" />
          </h4>
        </div>
      </PageBody>
    );
  }

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

export default OrderConfirmedLoadingWrapper;
