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

const PayPalCancelPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const bookingId = searchParams.get('bookingId');
  const [cancelling, setCancelling] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    if (!bookingId) return;

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

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

    const handleCancel = async () => {
      try {
        setCancelling(true);
        const response = await cancelPayPalPayment(Number(bookingId));
        
        if (response.success) {
          toast.info('Payment canceled. Your booking has been automatically cancelled.');
        }
      } catch (err: unknown) {
        // Don't show error if request was aborted
        if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
          return;
        }
        logger.error('Error canceling payment', err);
      } finally {
        setCancelling(false);
      }
    };

    handleCancel();

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

  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">
        {cancelling ? (
          <>
            <div className="w-16 h-16 sm:w-20 sm:h-20 bg-gradient-to-br from-orange-500/20 to-orange-600/20 
              rounded-full flex items-center justify-center mx-auto mb-4 sm:mb-6
              border border-orange-500/30 shadow-lg shadow-orange-500/20">
              <Loader2 className="w-10 h-10 sm:w-12 sm:h-12 text-orange-400 animate-spin" />
            </div>
            <h1 className="text-2xl sm:text-3xl font-serif font-semibold text-orange-300 mb-3 tracking-wide">
              Processing Cancellation
            </h1>
            <p className="text-gray-300/80 font-light text-base sm:text-lg mb-6 sm:mb-8 tracking-wide px-2">
              Canceling your payment and booking...
            </p>
          </>
        ) : (
          <>
            <div className="w-16 h-16 sm:w-20 sm:h-20 bg-gradient-to-br from-orange-500/20 to-orange-600/20 
              rounded-full flex items-center justify-center mx-auto mb-4 sm:mb-6
              border border-orange-500/30 shadow-lg shadow-orange-500/20">
              <XCircle className="w-10 h-10 sm:w-12 sm:h-12 text-orange-400" />
            </div>
            <h1 className="text-2xl sm:text-3xl font-serif font-semibold text-orange-300 mb-3 tracking-wide">
              Payment Cancelled
            </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">
              You cancelled the PayPal payment. No charges were made. Your booking has been automatically cancelled.
            </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 flex items-center justify-center gap-2
                disabled:opacity-50 disabled:cursor-not-allowed text-sm sm:text-base"
              disabled={cancelling}
            >
              <ArrowLeft className="w-4 h-4 sm:w-5 sm:h-5" />
              View Booking Details
            </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 PayPalCancelPage;

