'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import { Button } from '@kit/ui/button';
import { Trans } from '@kit/ui/trans';
import { placeOrder } from "@lib/data/cart"
import Link from 'next/link';
import GlobalLoader from '../../loading';

enum Status {
  LOADING = 'LOADING',
  ERROR = 'ERROR',
}

export function MontonioCheckoutCallback() {
  const router = useRouter();
  const [status, setStatus] = useState<Status>(Status.LOADING);
  const [isFinalized, setIsFinalized] = useState(false);
  const searchParams = useSearchParams();
  
  useEffect(() => {
    if (isFinalized) {
      return;
    }

    const token = searchParams.get('order-token');
    if (!token) {
      //router.push('/home/cart');
      return;
    }

    async function verifyToken() {
      setStatus(Status.LOADING);

      try {
        const response = await fetch('/api/montonio/verify-token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ token }),
        });
        setIsFinalized(true);

        if (!response.ok) {
          const body = await response.json();
          throw new Error(body.error ?? 'Failed to verify payment status.');
        }

        const body = await response.json();
        const paymentStatus = body.status as string;
        if (paymentStatus === 'PAID') {
          try {
            await placeOrder();
          } catch (e) {
            console.error("Error placing order", e);
            router.push('/home/cart');
          }
        } else {
          throw new Error('Payment failed or pending');
        }
      } catch (e) {
        console.error("Error verifying token", e);
        setStatus(Status.ERROR);
      }
    }

    void verifyToken();
  }, [searchParams, isFinalized]);

  if (status === Status.ERROR) {
    return (
      <div className={'flex flex-col space-y-4'}>
        <Alert variant={'destructive'}>
          <AlertTitle>
            <Trans i18nKey={'checkout.error.title'} />
          </AlertTitle>

          <AlertDescription>
            <p>
              <Trans i18nKey={'checkout.error.description'} />
            </p>
          </AlertDescription>
        </Alert>

        <div className={'flex'}>
          <Button asChild>
            <Link href={'/home'}>
              <Trans i18nKey={'checkout.goToDashboard'} />
            </Link>
          </Button>
        </div>
      </div>
    );
  }

  return <GlobalLoader />;
}
