import React, { useEffect, useState, useRef } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { capturePayPalPayment, cancelPayPalPayment } from '../../features/payments/services/paymentService';
import { toast } from 'react-toastify';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { logger } from '../../shared/utils/logger';

const PayPalReturnPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  const orderId = searchParams.get('token');
  const bookingId = searchParams.get('bookingId');

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    const capturePayment = async () => {
      if (!orderId || !bookingId) {
        setError('Missing payment information');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const response = await capturePayPalPayment(orderId, Number(bookingId));

        if (response.success) {
          setSuccess(true);
          toast.success('Payment confirmed successfully!');
          
          setTimeout(() => {
            navigate(`/bookings/${bookingId}`);
          }, 2000);
        } else {
          setError(response.message || 'Payment capture failed');
          toast.error(response.message || 'Payment capture failed');
          
          
          try {
            await cancelPayPalPayment(Number(bookingId));
          } catch (cancelErr) {
            logger.error('Error canceling payment after capture failure', cancelErr);
          }
        }
      } catch (err: unknown) {
        // Don't show error if request was aborted
        if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
          return;
        }
        const errorMessage = (err && typeof err === 'object' && 'response' in err && err.response && typeof err.response === 'object' && 'data' in err.response && err.response.data && typeof err.response.data === 'object' && 'message' in err.response.data && typeof err.response.data.message === 'string' ? err.response.data.message : undefined) || (err instanceof Error ? err.message : undefined) || 'Failed to capture payment';
        setError(errorMessage);
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    capturePayment();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, [orderId, bookingId, navigate]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] 
        flex items-center justify-center py-8 sm:py-12 px-4 sm:px-6 lg:px-8">
        <div className="text-center w-full max-w-2xl mx-auto">
          <div className="w-16 h-16 sm:w-20 sm:h-20 bg-gradient-to-br from-[var(--luxury-gold)]/20 to-[var(--luxury-gold-light)]/20 
            rounded-full flex items-center justify-center mx-auto mb-4 sm:mb-6
            border border-[var(--luxury-gold)]/30 shadow-lg shadow-[var(--luxury-gold)]/20">
            <Loader2 className="w-10 h-10 sm:w-12 sm:h-12 text-[var(--luxury-gold)] animate-spin" />
          </div>
          <p className="text-gray-300/80 font-light text-base sm:text-lg tracking-wide">
            Processing your payment...
          </p>
        </div>
      </div>
    );
  }

  if (success) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] 
        flex items-center justify-center py-8 sm:py-12 px-4 sm:px-6 lg:px-8">
        <div className="bg-gradient-to-br from-gray-900/40 to-gray-800/20 
          border border-gray-700/50 rounded-xl p-6 sm:p-10 w-full max-w-2xl mx-auto text-center 
          backdrop-blur-xl shadow-2xl shadow-black/20">
          <div className="w-16 h-16 sm:w-20 sm:h-20 bg-gradient-to-br from-green-500/20 to-green-600/20 
            rounded-full flex items-center justify-center mx-auto mb-4 sm:mb-6
            border border-green-500/30 shadow-lg shadow-green-500/20">
            <CheckCircle className="w-10 h-10 sm:w-12 sm:h-12 text-green-400" />
          </div>
          <h1 className="text-2xl sm:text-3xl font-serif font-semibold text-green-300 mb-3 tracking-wide">
            Payment Successful!
          </h1>
          <p className="text-gray-300/80 font-light text-base sm:text-lg mb-6 sm:mb-8 tracking-wide px-2">
            Your payment has been confirmed. Redirecting to booking details...
          </p>
          <button
            onClick={() => navigate(`/bookings/${bookingId}`)}
            className="bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
              text-[#0f0f0f] px-6 py-2 sm:px-8 sm:py-3 rounded-sm 
              hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] 
              transition-all duration-300 font-medium tracking-wide 
              shadow-lg shadow-[var(--luxury-gold)]/30 text-sm sm:text-base w-full sm:w-auto"
          >
            View Booking
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] 
      flex items-center justify-center py-8 sm:py-12 px-4 sm:px-6 lg:px-8">
      <div className="bg-gradient-to-br from-gray-900/40 to-gray-800/20 
        border border-gray-700/50 rounded-xl p-6 sm:p-10 w-full max-w-2xl text-center 
        backdrop-blur-xl shadow-2xl shadow-black/20">
        <div className="w-16 h-16 sm:w-20 sm:h-20 bg-gradient-to-br from-red-500/20 to-red-600/20 
          rounded-full flex items-center justify-center mx-auto mb-4 sm:mb-6
          border border-red-500/30 shadow-lg shadow-red-500/20">
          <XCircle className="w-10 h-10 sm:w-12 sm:h-12 text-red-400" />
        </div>
        <h1 className="text-2xl sm:text-3xl font-serif font-semibold text-red-300 mb-3 tracking-wide">
          Payment Failed
        </h1>
        <p className="text-gray-300/80 font-light text-base sm:text-lg mb-6 sm:mb-8 tracking-wide leading-relaxed px-2">
          {error || 'Unable to process your payment. Please try again.'}
        </p>
        <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
          {bookingId && (
            <button
              onClick={() => navigate(`/bookings/${bookingId}`)}
              className="flex-1 bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
                text-[#0f0f0f] px-4 py-2 sm:px-6 sm:py-3 rounded-sm 
                hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] 
                transition-all duration-300 font-medium tracking-wide 
                shadow-lg shadow-[var(--luxury-gold)]/30 text-sm sm:text-base"
            >
              View Booking
            </button>
          )}
          <button
            onClick={() => navigate('/bookings')}
            className="flex-1 bg-gradient-to-br from-gray-800/40 to-gray-700/20 
              border border-gray-600/30 text-gray-300 px-4 py-2 sm:px-6 sm:py-3 rounded-sm 
              hover:border-[var(--luxury-gold)]/50 hover:text-[var(--luxury-gold)] 
              transition-all duration-300 font-light tracking-wide
              backdrop-blur-sm text-sm sm:text-base"
          >
            My Bookings
          </button>
        </div>
      </div>
    </div>
  );
};

export default PayPalReturnPage;

