'use client';

import { useEffect, useState } from 'react';

import { useRouter } from 'next/navigation';

import { processMontonioCallback } from './actions';

export default function MontonioCallbackClient({
  orderToken,
  error,
}: {
  orderToken?: string;
  error?: string;
}) {
  const router = useRouter();

  const [isProcessing, setIsProcessing] = useState(false);
  const [hasProcessed, setHasProcessed] = useState(false);

  useEffect(() => {
    if (error) {
      console.error(error);
      router.push('/home/cart/montonio-callback/error');
      return;
    }

    if (!orderToken || hasProcessed || isProcessing) {
      return;
    }

    const processOrder = async () => {
      setIsProcessing(true);
      setHasProcessed(true);

      try {
        const result = await processMontonioCallback(orderToken);
        if (result.success) {
          return router.push(`/home/order/${result.orderId}/confirmed`);
        }
        if (result.failedServiceBookings?.length) {
          router.push(
            `/home/cart/montonio-callback/error?reasonFailed=${result.failedServiceBookings.map(({ reason }) => reason).join(',')}`,
          );
        }
      } catch (error) {
        console.error('Failed to place order', error);
        router.push('/home/cart/montonio-callback/error');
      } finally {
        setIsProcessing(false);
      }
    };

    processOrder();
  }, [orderToken, error, router, hasProcessed, isProcessing]);

  return (
    <div className="mt-10 flex min-h-screen justify-center">
      <div className="text-center">
        <div className="border-primary mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2"></div>
      </div>
    </div>
  );
}
