'use client';

import { useEffect, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { usePaymentStore } from '@/lib/payment-store';
import { apiClient } from '@/lib/api-client';
import { CheckCircle, Loader2 } from 'lucide-react';

function WaafiSuccessContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { bookingId } = useBookingStore();
  const { updateStatus } = usePaymentStore();
  const [status, setStatus] = useState<'processing' | 'done' | 'error'>('processing');

  // Waafi callback query params
  const accountNo    = searchParams.get('accountNo')    || '';
  const currency     = searchParams.get('currency')     || '';
  const referenceId  = searchParams.get('referenceId')  || '';
  const state        = searchParams.get('state')        || '';
  const transactionId = searchParams.get('transactionId') || '';
  const txAmount     = searchParams.get('txAmount')     || '';
  const timestamp    = searchParams.get('timestamp')    || '';
  const bookingIdQp  = searchParams.get('bookingId')    || bookingId || '';

  useEffect(() => {
    const confirm = async () => {
      try {
        if (bookingIdQp) {
          await apiClient.patch(`/bookings/${bookingIdQp}/confirm`, {
            paymentReference: referenceId || transactionId,
            paymentMethod: 'WAAFI',
            transactionDetails: {
              transactionId,
              accountNo,
              amount: txAmount,
              currency,
              state,
              timestamp,
            },
          });
        }

        updateStatus('SUCCEEDED');
        setStatus('done');
        setTimeout(() => router.push('/booking/confirmation'), 1500);
      } catch (err: any) {
        updateStatus('SUCCEEDED');
        setStatus('done');
        setTimeout(() => router.push('/booking/confirmation'), 1500);
      }
    };

    confirm();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4">
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8 max-w-md w-full text-center">
        {status === 'processing' && (
          <>
            <Loader2 className="w-14 h-14 text-primary animate-spin mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Confirming payment…</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">Please wait while we confirm your Waafi payment.</p>
          </>
        )}
        {status === 'done' && (
          <>
            <CheckCircle className="w-14 h-14 text-green-500 mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Payment Successful!</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">Your Waafi payment was received.</p>
            {transactionId && <p className="text-xs text-gray-400">Transaction ID: {transactionId}</p>}
            {referenceId && <p className="text-xs text-gray-400">Reference: {referenceId}</p>}
            {txAmount && currency && (
              <p className="text-xs text-gray-400">Amount: {txAmount} {currency}</p>
            )}
            <p className="text-xs text-gray-400 mt-3">Redirecting to your booking confirmation…</p>
          </>
        )}
      </div>
    </div>
  );
}

export default function WaafiSuccessPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center"><Loader2 className="w-10 h-10 animate-spin text-primary" /></div>}>
      <WaafiSuccessContent />
    </Suspense>
  );
}
