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

const BoricaReturnPage: 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 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 confirmPayment = async () => {
      if (!bookingId) {
        setError('Missing booking information');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        
        // Extract all parameters from URL (Borica sends POST data, but we'll handle GET params)
        const responseData: Record<string, string> = {};
        searchParams.forEach((value, key) => {
          responseData[key] = value;
        });

        // If no params, try to get from POST data (would need server-side handling)
        // For now, we'll use the bookingId to fetch payment status
        if (Object.keys(responseData).length === 0 || !responseData.ORDER) {
          // Try to confirm with booking ID only
          // In a real implementation, Borica would POST the data to a server endpoint
          setError('Payment response data not found. Please check your payment status.');
          setLoading(false);
          return;
        }

        const response = await confirmBoricaPayment(responseData);

        if (response.success) {
          setSuccess(true);
          toast.success('Payment confirmed successfully!');
          
          setTimeout(() => {
            navigate(`/bookings/${bookingId}`);
          }, 2000);
        } else {
          setError(response.message || 'Payment confirmation failed');
          toast.error(response.message || 'Payment confirmation failed');
        }
      } catch (err: unknown) {
        const isAbortError = (e: unknown): boolean => {
          if (typeof e === 'object' && e !== null) {
            const error = e as { name?: string; code?: string };
            return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
          }
          return false;
        };
        if (isAbortError(err)) {
          return;
        }
        const errorMessage = getUserFriendlyError(err) || getUserFriendlyError(err) || 'Failed to confirm payment';
        setError(errorMessage);
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    confirmPayment();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, [bookingId, searchParams, 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="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">
          <Loader2 className="w-12 h-12 sm:w-16 sm:h-16 animate-spin text-[var(--luxury-gold)] mx-auto mb-4" />
          <h1 className="text-xl sm:text-2xl font-serif font-semibold text-white mb-2">
            Processing Payment...
          </h1>
          <p className="text-gray-400 text-sm sm:text-base">
            Please wait while we confirm 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-red-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-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 px-2">
          {error || 'There was an issue processing your payment. Please try again or contact support.'}
        </p>
        <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 justify-center">
          <button
            onClick={() => navigate(`/bookings/${bookingId}`)}
            className="bg-gray-700/50 text-gray-300 px-6 py-2 sm:px-8 sm:py-3 rounded-sm 
              hover:bg-gray-700 transition-all duration-300 font-medium tracking-wide 
              text-sm sm:text-base w-full sm:w-auto"
          >
            View Booking
          </button>
          <button
            onClick={() => navigate('/')}
            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"
          >
            Go Home
          </button>
        </div>
      </div>
    </div>
  );
};

export default BoricaReturnPage;

