import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { useConfirmCardPaymentMutation } from '../Redux/services/cards.service';
import { toast } from 'sonner';
import Navbar from '../components/Navbar';
import { Footer } from '../components/Footer';

interface PaymentSuccessPageProps {
  onHomeClick: () => void;
  onPassesClick: () => void;
  onSignInClick: () => void;
  onSignOutClick?: () => void;
  currentPage?: string;
  user?: { email: string; name: string } | null;
}

export function PaymentSuccessPage({
  onHomeClick,
  onPassesClick,
  onSignInClick,
  onSignOutClick,
  currentPage,
  user,
}: PaymentSuccessPageProps) {
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get('session_id');
  const [confirmPayment, { isLoading }] = useConfirmCardPaymentMutation();
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
  const [errorMsg, setErrorMsg] = useState<string>('');
  const navigate = useNavigate();

  useEffect(() => {
    const confirm = async () => {
      //  Try multiple sources for bookingId
      let bookingId = localStorage.getItem('pendingBookingId');
      if (!bookingId) {
        bookingId = sessionStorage.getItem('pendingBookingId');
      }
      // Optional: if you have bookingId in URL query param (e.g., ?bookingId=123)
      const urlBookingId = searchParams.get('bookingId');
      if (!bookingId && urlBookingId) {
        bookingId = urlBookingId;
      }

      console.log('Retrieved bookingId:', bookingId);
      console.log('SessionId from URL:', sessionId);

      if (!bookingId) {
        setStatus('error');
        setErrorMsg(
          'Missing booking information. Please contact support with your order reference. ' +
          'If you just completed payment, your order may still be processing.'
        );
        return;
      }

      if (!sessionId) {
        setStatus('error');
        setErrorMsg('Missing session ID. Please contact support.');
        return;
      }

      try {
        await confirmPayment({ bookingId, sessionId }).unwrap();
        setStatus('success');
        toast.success('Payment confirmed! Your order is complete.');
        // Clean up storage
        localStorage.removeItem('pendingBookingId');
        sessionStorage.removeItem('pendingBookingId');
      } catch (err: any) {
        console.error('Payment confirmation error:', err);
        setStatus('error');
        setErrorMsg(err?.data?.message || 'Payment could not be confirmed. Please contact support.');
        toast.error('Payment confirmation failed');
        // Clean up storage to avoid infinite loops
        localStorage.removeItem('pendingBookingId');
        sessionStorage.removeItem('pendingBookingId');
      }
    };

    confirm();
  }, [sessionId, confirmPayment, searchParams]);

  return (
    <div className="min-h-screen bg-[#fafafa] font-poppins">
      <Navbar
        activeCity="Melbourne"
        onCityChange={() => {}}
        onSignInClick={onSignInClick}
        onSignOutClick={onSignOutClick}
        onHomeClick={onHomeClick}
        onPassesClick={onPassesClick}
        onCheckoutClick={() => {}}
        onAttractionsClick={() => {}}
        onBlogsClick={() => {}}
        onHowItWorksClick={() => {}}
        onFAQClick={() => {}}
        onPrivacyPolicyClick={() => {}}
        onAboutUsClick={() => {}}
        onProfileClick={() => {}}
        onCityCardsClick={() => {}}
        onMagicItineraryClick={() => {}}
        onPostCardsClick={() => {}}
        onOffersClick={() => {}}
        onSuperSavingsClick={() => {}}
        onEsimsClick={() => {}}
        onHotelDiscountsClick={() => {}}
        onCartClick={() => {}}
        currentPage={currentPage as any}
        user={user}
      />

      <div className="w-full px-4 sm:px-6 lg:px-10 xl:px-16 pt-32 pb-24 max-w-[1440px] mx-auto flex justify-center items-center min-h-[60vh]">
        <div className="bg-white rounded-2xl shadow-lg p-8 max-w-md w-full text-center">
          {status === 'loading' && (
            <>
              <Loader2 className="w-16 h-16 text-[#F95F62] animate-spin mx-auto mb-4" />
              <h2 className="text-2xl font-semibold text-[#2a2a2a]">Confirming your payment...</h2>
              <p className="text-[#555] mt-2">Please wait while we verify your transaction.</p>
            </>
          )}

          {status === 'success' && (
            <>
              <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
              <h2 className="text-2xl font-semibold text-[#2a2a2a]">Payment Successful!</h2>
              <p className="text-[#555] mt-2">Thank you for your purchase. Your order is now confirmed.</p>
              <button
                onClick={() => navigate('/my-orders')}
                className="mt-6 px-6 py-3 bg-[#F95F62] text-white rounded-xl font-medium hover:bg-[#e8545a] transition"
              >
                View My Orders
              </button>
            </>
          )}

          {status === 'error' && (
            <>
              <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
              <h2 className="text-2xl font-semibold text-[#2a2a2a]">Payment Confirmation Failed</h2>
              <p className="text-red-500 mt-2">{errorMsg}</p>
              <button
                onClick={() => navigate('/')}
                className="mt-6 px-6 py-3 bg-gray-200 text-[#2a2a2a] rounded-xl font-medium hover:bg-gray-300 transition"
              >
                Go to Homepage
              </button>
            </>
          )}
        </div>
      </div>

      <Footer
        onHomeClick={onHomeClick}
        onPassesClick={onPassesClick}
        onAttractionsClick={() => {}}
        onBlogsClick={() => {}}
        onHowItWorksClick={() => {}}
        onFAQClick={() => {}}
        onPrivacyPolicyClick={() => {}}
        onAboutUsClick={() => {}}
        onContactUsClick={() => {}}
      />
    </div>
  );
}