'use client';

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

type IntentStatus = 'PENDING' | 'PROCESSING' | 'REQUIRES_ACTION' | 'SUCCEEDED' | 'FAILED';
type ViewState = 'checking' | 'succeeded' | 'failed' | 'unknown';

// Waafi registers a dedicated success URL, but a hit here still isn't proof of payment on
// its own (gateway redirect vs. real settlement can disagree). Poll the backend (which
// reconciles with the provider) before showing "Payment Successful".
async function verifyBookingPaid(bookingId: string): Promise<'SUCCEEDED' | 'FAILED' | 'UNKNOWN'> {
  const maxAttempts = 5;
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      const intent = await apiClient.get<{ status: IntentStatus }>(`/payments/intents/${bookingId}`);
      if (intent?.status === 'SUCCEEDED') return 'SUCCEEDED';
      if (intent?.status === 'FAILED') return 'FAILED';
    } catch {
      // transient lookup failure — keep retrying until attempts are exhausted
    }
    if (attempt < maxAttempts - 1) {
      await new Promise((resolve) => setTimeout(resolve, 1500));
    }
  }
  return 'UNKNOWN';
}

function WaafiSuccessContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { updateStatus } = usePaymentStore();
  const { bookingId } = useBookingStore();
  const [view, setView] = useState<ViewState>('checking');
  const [returnTarget, setReturnTarget] = useState('/booking/confirmation');

  // Waafi callback query params
  const referenceId   = searchParams.get('referenceId')   || '';
  const transactionId = searchParams.get('transactionId') || '';
  const txAmount      = searchParams.get('txAmount')       || '';
  const currency      = searchParams.get('currency')       || '';

  useEffect(() => {
    let cancelled = false;

    const manageBookingRef = consumeManageBookingPaymentReturn();
    const target = manageBookingRef ? `/booking/detail?ref=${encodeURIComponent(manageBookingRef)}` : '/booking/confirmation';
    setReturnTarget(target);

    // Manage Booking sessions don't carry a bookingId in the client store — the detail page
    // it lands on re-fetches the booking's real status itself, so there's nothing to verify
    // client-side here; just hand off without claiming an outcome we can't confirm.
    if (manageBookingRef) {
      router.push(target);
      return;
    }

    // Normal booking flow: bookingId comes from a Zustand store persisted to localStorage.
    // This page is always reached via a real cross-domain redirect from the payment gateway
    // (a full page load, not an in-app navigation), so that store has to rehydrate from
    // localStorage asynchronously — bookingId can read as empty on the first render or two.
    // Wait for it instead of treating an empty first-render value as "nothing to verify",
    // which would silently skip this page's whole verification step and hand off to
    // /booking/confirmation without ever having checked payment status here.
    if (!bookingId) return;

    verifyBookingPaid(bookingId).then((result) => {
      if (cancelled) return;
      if (result === 'SUCCEEDED') {
        updateStatus('SUCCEEDED');
        setView('succeeded');
        setTimeout(() => router.push(target), 1500);
      } else if (result === 'FAILED') {
        updateStatus('FAILED');
        setView('failed');
      } else {
        // Still not confirmed after polling — don't claim success or failure. Hand off to
        // /booking/confirmation, which now reflects the booking's real (pending) status.
        setView('unknown');
        setTimeout(() => router.push(target), 1500);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [bookingId, router, updateStatus]);

  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">
        {view === 'checking' && (
          <>
            <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>
          </>
        )}
        {view === 'succeeded' && (
          <>
            <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…</p>
          </>
        )}
        {view === 'failed' && (
          <>
            <XCircle className="w-14 h-14 text-red-500 mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Payment Failed</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">Your Waafi payment was not completed.</p>
            <button onClick={() => router.push(returnTarget)}
              className="btn-secondary w-full flex items-center justify-center gap-2">
              <ChevronLeft className="w-4 h-4" />
              Back
            </button>
          </>
        )}
        {view === 'unknown' && (
          <>
            <Loader2 className="w-14 h-14 text-amber-500 animate-spin mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Still confirming…</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              We haven&apos;t received final confirmation from Waafi yet. Taking you to your booking status.
            </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>
  );
}
