import React, { useState, useEffect } from 'react';
import {
  X,
  CheckCircle,
  AlertCircle,
  CreditCard,
  XCircle,
  Loader2,
} from 'lucide-react';
import { toast } from 'react-toastify';
import { getBookingById, type Booking } from '../../bookings/services/bookingService';
import CancelBookingModal from '../../bookings/components/CancelBookingModal';
import {
  getPaymentsByBookingId,
  type Payment,
} from '../services/paymentService';
import { useFormatCurrency } from '../hooks/useFormatCurrency';
import StripePaymentModal from './StripePaymentModal';
import PayPalPaymentModal from './PayPalPaymentModal';

interface DepositPaymentModalProps {
  isOpen: boolean;
  bookingId: number;
  onSuccess: () => void;
  onClose: () => void;
}

const DepositPaymentModal: React.FC<DepositPaymentModalProps> = ({
  isOpen,
  bookingId,
  onSuccess,
  onClose,
}) => {
  const { formatCurrency, currency } = useFormatCurrency();
  const [booking, setBooking] = useState<Booking | null>(null);
  const [depositPayment, setDepositPayment] = useState<Payment | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [, setPaymentSuccess] = useState(false);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<'stripe' | 'paypal' | null>(null);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [showCancelModal, setShowCancelModal] = useState(false);

  useEffect(() => {
    if (isOpen && bookingId) {
      fetchData(bookingId);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, bookingId]);

  useEffect(() => {
    if (!isOpen) {
      setBooking(null);
      setDepositPayment(null);
      setPaymentSuccess(false);
      setSelectedPaymentMethod(null);
      setShowPaymentModal(false);
      setError(null);
    }
  }, [isOpen]);

  const fetchData = async (id: number) => {
    try {
      setLoading(true);
      setError(null);

      const bookingResponse = await getBookingById(id);
      if (!bookingResponse.success || !bookingResponse.data?.booking) {
        throw new Error('Booking not found');
      }

      const bookingData = bookingResponse.data.booking;
      setBooking(bookingData);

      // Close modal if booking is cancelled
      if (bookingData.status === 'cancelled') {
        toast.info('This booking has been cancelled');
        onClose();
        return;
      }

      if (bookingData.status === 'confirmed' || bookingData.status === 'checked_in') {
        toast.success('Booking is already confirmed!');
        onSuccess();
        onClose();
        return;
      }

      if (!bookingData.requires_deposit) {
        toast.info('This booking does not require a deposit');
        onSuccess();
        onClose();
        return;
      }

      const paymentsResponse = await getPaymentsByBookingId(id);
      if (paymentsResponse.success) {
        const deposit = paymentsResponse.data.payments.find(
          (p) => p.payment_type === 'deposit'
        );
        if (deposit) {
          setDepositPayment(deposit);
          if (deposit.payment_status === 'completed') {
            setPaymentSuccess(true);
          }
        }
      }
    } catch (err: unknown) {
      console.error('Error fetching data:', err);
      const message =
        getUserFriendlyError(err) || 'Unable to load payment information';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const handleCancelBookingClick = () => {
    setShowCancelModal(true);
  };

  const handleCancelSuccess = () => {
    setShowCancelModal(false);
    onClose();
    onSuccess();
  };

  const handlePaymentMethodSelect = (method: 'stripe' | 'paypal') => {
    setSelectedPaymentMethod(method);
    setShowPaymentModal(true);
  };

  const handlePaymentSuccess = async () => {
    setShowPaymentModal(false);
    setPaymentSuccess(true);
    setSelectedPaymentMethod(null);
    
    // Check booking status before showing success toast
    try {
      const bookingResponse = await getBookingById(bookingId);
      if (bookingResponse.success && bookingResponse.data?.booking) {
        const bookingData = bookingResponse.data.booking;
        // Only show success toast if booking is not cancelled
        if (bookingData.status !== 'cancelled') {
          toast.success('✅ Deposit payment successful! Your booking has been confirmed.');
        }
      }
    } catch (err) {
      // If we can't check status, don't show toast to avoid confusion
      console.error('Error checking booking status:', err);
    }
    
    setTimeout(() => {
      onSuccess();
      onClose();
    }, 1500);
  };

  const handlePaymentClose = () => {
    setShowPaymentModal(false);
    setSelectedPaymentMethod(null);
    // When payment is canceled, close the deposit modal entirely
    // User can reopen it from booking details if needed
    onClose();
  };

  if (!isOpen) return null;

  const depositAmount = depositPayment ? parseFloat(depositPayment.amount.toString()) : 0;
  const remainingAmount = booking ? booking.total_price - depositAmount : 0;
  const isDepositPaid = depositPayment?.payment_status === 'completed';

  return (
    <>
      <div className="fixed inset-0 z-[10000] flex items-center justify-center p-2 sm:p-4">
        <div
          className="fixed inset-0 bg-black/90 backdrop-blur-sm"
          onClick={onClose}
        />
        <div className="relative w-full max-w-3xl max-h-[95vh] bg-gradient-to-br from-[#0a0a0a] via-[#1a1a1a] to-[#0a0a0a] rounded-xl sm:rounded-2xl border border-[var(--luxury-gold)]/30 shadow-2xl shadow-[var(--luxury-gold)]/20 overflow-hidden flex flex-col">
          {/* Header */}
          <div className="px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-[var(--luxury-gold)]/20 bg-gradient-to-r from-[#1a1a1a] to-[#0a0a0a] flex-shrink-0">
            <div className="flex items-center justify-between gap-2">
              <div className="min-w-0 flex-1">
                <h2 className="text-base sm:text-lg md:text-xl font-serif font-bold text-white tracking-tight truncate">
                  Deposit Payment
                </h2>
                {booking && (
                  <p className="text-xs text-gray-400 mt-0.5 truncate">
                    Booking #{booking.booking_number}
                  </p>
                )}
              </div>
              <div className="flex items-center gap-1.5 sm:gap-2 flex-shrink-0">
                {!isDepositPaid && booking && (
                  <button
                    onClick={handleCancelBookingClick}
                    className="px-2 sm:px-3 py-1 sm:py-1.5 text-xs bg-red-500/10 border border-red-500/30 text-red-300 rounded-lg hover:bg-red-500/20 transition-colors flex items-center gap-1 sm:gap-1.5 min-h-[32px] sm:min-h-[36px]"
                  >
                    <XCircle className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
                    <span className="hidden xs:inline">Cancel Booking</span>
                    <span className="xs:hidden">Cancel</span>
                  </button>
                )}
                <button
                  onClick={onClose}
                  className="p-1.5 sm:p-2 hover:bg-[var(--luxury-gold)]/10 rounded-lg transition-colors text-gray-400 hover:text-white flex-shrink-0"
                >
                  <X className="w-4 h-4 sm:w-5 sm:h-5" />
                </button>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto px-3 sm:px-4 md:px-6 py-4 sm:py-6">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-8 sm:py-12">
                <Loader2 className="w-10 h-10 sm:w-12 sm:h-12 animate-spin text-[var(--luxury-gold)] mb-3 sm:mb-4" />
                <p className="text-xs sm:text-sm text-gray-400">Loading payment information...</p>
              </div>
            ) : error || !booking || !depositPayment ? (
              <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-4 sm:p-6 text-center">
                <AlertCircle className="w-10 h-10 sm:w-12 sm:h-12 text-red-400 mx-auto mb-3 sm:mb-4" />
                <p className="text-xs sm:text-sm text-red-300 font-medium mb-3 sm:mb-4">
                  {error || 'Payment information not found'}
                </p>
                <button
                  onClick={onClose}
                  className="px-4 py-2 sm:py-2.5 bg-[var(--luxury-gold)] text-black font-semibold rounded-lg hover:bg-[var(--luxury-gold-dark)] transition-all text-sm sm:text-base min-h-[44px]"
                >
                  Close
                </button>
              </div>
            ) : (
              <div className="space-y-4 sm:space-y-6">
                {/* Success Message */}
                {isDepositPaid && (
                  <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-3 sm:p-4">
                    <div className="flex items-start gap-2 sm:gap-3">
                      <div className="w-10 h-10 sm:w-12 sm:h-12 bg-green-500/20 rounded-full flex items-center justify-center border border-green-500/30 flex-shrink-0">
                        <CheckCircle className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-green-400" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="text-base sm:text-lg font-serif font-semibold text-green-300 mb-1">
                          Deposit Payment Successful!
                        </h3>
                        <p className="text-xs sm:text-sm text-green-200/80 leading-relaxed">
                          Your booking has been confirmed. Remaining amount to be paid on arrival at the hotel.
                        </p>
                        {depositPayment.payment_date && (
                          <p className="text-xs text-green-300/70 mt-2">
                            Paid on: {new Date(depositPayment.payment_date).toLocaleString('en-US')}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                )}

                {/* Payment Required Message */}
                {!isDepositPaid && (
                  <div className="bg-[var(--luxury-gold)]/10 border border-[var(--luxury-gold)]/30 rounded-lg p-3 sm:p-4">
                    <div className="flex items-start gap-2 sm:gap-3">
                      <div className="w-10 h-10 sm:w-12 sm:h-12 bg-[var(--luxury-gold)]/20 rounded-full flex items-center justify-center border border-[var(--luxury-gold)]/30 flex-shrink-0">
                        <CreditCard className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-[var(--luxury-gold)]" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="text-base sm:text-lg font-serif font-semibold text-[var(--luxury-gold)] mb-1">
                          Deposit Payment Required
                        </h3>
                        <p className="text-xs sm:text-sm text-gray-300 leading-relaxed">
                          Please pay <strong className="text-[var(--luxury-gold)]">20% deposit</strong> to confirm your booking. Pay the remaining balance on arrival at the hotel.
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {/* Payment Information */}
                <div className="bg-[#0a0a0a] border border-[var(--luxury-gold)]/20 rounded-lg p-3 sm:p-4">
                  <h3 className="text-xs sm:text-sm font-semibold text-[var(--luxury-gold)] mb-2 sm:mb-3">Payment Information</h3>
                  <div className="space-y-1.5 sm:space-y-2 text-xs sm:text-sm">
                    <div className="flex justify-between text-gray-300">
                      <span>Total Room Price</span>
                      <span>{formatCurrency(booking.total_price)}</span>
                    </div>
                    <div className="flex justify-between text-base sm:text-lg font-bold text-[var(--luxury-gold)] pt-2 border-t border-[var(--luxury-gold)]/20">
                      <span className="break-words pr-2">Deposit Amount (20%)</span>
                      <span className="flex-shrink-0">{formatCurrency(depositAmount)}</span>
                    </div>
                    <div className="flex justify-between text-xs text-gray-400 pt-1">
                      <span>Remaining at check-in</span>
                      <span>{formatCurrency(remainingAmount)}</span>
                    </div>
                  </div>
                </div>

                {/* Payment Method Selection */}
                {!isDepositPaid && !selectedPaymentMethod && (
                  <div className="bg-[#0a0a0a] border border-[var(--luxury-gold)]/20 rounded-lg p-3 sm:p-4">
                    <h3 className="text-xs sm:text-sm font-semibold text-[var(--luxury-gold)] mb-2 sm:mb-3">Choose Payment Method</h3>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
                      <button
                        onClick={() => handlePaymentMethodSelect('stripe')}
                        className="p-3 sm:p-4 bg-[#1a1a1a] border-2 border-gray-600/30 rounded-lg hover:border-[var(--luxury-gold)]/50 transition-all text-left group min-h-[80px] sm:min-h-[100px]"
                      >
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                          <div className="w-8 h-8 sm:w-10 sm:h-10 bg-indigo-500/20 rounded-lg flex items-center justify-center border border-indigo-500/30 flex-shrink-0">
                            <CreditCard className="w-4 h-4 sm:w-5 sm:h-5 text-indigo-400 group-hover:text-[var(--luxury-gold)] transition-colors" />
                          </div>
                          <span className="text-xs font-semibold text-indigo-400 group-hover:text-[var(--luxury-gold)] transition-colors">
                            Card Payment
                          </span>
                        </div>
                        <p className="text-xs text-gray-400 group-hover:text-gray-300 transition-colors leading-relaxed">
                          Pay with credit or debit card via Stripe
                        </p>
                      </button>

                      <button
                        onClick={() => handlePaymentMethodSelect('paypal')}
                        className="p-3 sm:p-4 bg-[#1a1a1a] border-2 border-gray-600/30 rounded-lg hover:border-[var(--luxury-gold)]/50 transition-all text-left group min-h-[80px] sm:min-h-[100px]"
                      >
                        <div className="flex items-center justify-between mb-1.5 sm:mb-2">
                          <div className="w-8 h-8 sm:w-10 sm:h-10 bg-blue-500/20 rounded-lg flex items-center justify-center border border-blue-500/30 flex-shrink-0">
                            <svg
                              className="w-4 h-4 sm:w-5 sm:h-5 text-blue-400 group-hover:text-[var(--luxury-gold)] transition-colors"
                              viewBox="0 0 24 24"
                              fill="currentColor"
                            >
                              <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.203zm14.146-14.42a.477.477 0 0 0-.414-.24h-3.84c-.48 0-.856.355-.932.826-.075.47-.232 1.21-.232 1.21s-.156-.74-.232-1.21a.957.957 0 0 0-.932-.826H5.342a.957.957 0 0 0-.932.826c-.076.47-.232 1.21-.232 1.21s-.156-.74-.232-1.21a.957.957 0 0 0-.932-.826H.477a.477.477 0 0 0-.414.24c-.11.19-.14.426-.08.643.06.217.2.4.388.51l.04.02c.19.11.426.14.643.08.217-.06.4-.2.51-.388l.01-.02c.11-.19.14-.426.08-.643a.955.955 0 0 0-.388-.51l-.01-.01a.955.955 0 0 0-.51-.388.955.955 0 0 0-.643.08l-.01.01a.955.955 0 0 0-.388.51c-.06.217-.03.453.08.643l.01.02c.11.188.293.328.51.388.217.06.453.03.643-.08l.01-.02c.188-.11.328-.293.388-.51.06-.217.03-.453-.08-.643l-.01-.01z"/>
                            </svg>
                          </div>
                          <span className="text-xs font-semibold text-blue-400 group-hover:text-[var(--luxury-gold)] transition-colors">
                            PayPal
                          </span>
                        </div>
                        <p className="text-xs text-gray-400 group-hover:text-gray-300 transition-colors leading-relaxed">
                          Pay securely with your PayPal account
                        </p>
                      </button>
                    </div>
                  </div>
                )}

                {/* Change Payment Method */}
                {!isDepositPaid && selectedPaymentMethod && (
                  <div className="bg-[#0a0a0a] border border-[var(--luxury-gold)]/20 rounded-lg p-3 sm:p-4">
                    <div className="flex items-center justify-between gap-2 mb-2 sm:mb-3">
                      <div className="min-w-0 flex-1">
                        <h3 className="text-xs sm:text-sm font-semibold text-[var(--luxury-gold)]">
                          {selectedPaymentMethod === 'stripe' ? 'Card Payment' : 'PayPal Payment'}
                        </h3>
                        <p className="text-xs text-gray-400 mt-0.5 sm:mt-1">
                          Pay deposit of {formatCurrency(depositAmount)}
                        </p>
                      </div>
                      <button
                        onClick={() => {
                          setSelectedPaymentMethod(null);
                          setShowPaymentModal(false);
                        }}
                        className="text-xs text-gray-400 hover:text-[var(--luxury-gold)] underline transition-colors flex-shrink-0 whitespace-nowrap"
                      >
                        Change method
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Payment Modals */}
      {showPaymentModal && booking && depositPayment && selectedPaymentMethod && (
        <>
          {selectedPaymentMethod === 'stripe' && (
            <StripePaymentModal
              isOpen={showPaymentModal}
              bookingId={booking.id}
              amount={depositAmount}
              currency={currency || 'USD'}
              onSuccess={handlePaymentSuccess}
              onClose={handlePaymentClose}
            />
          )}
          {selectedPaymentMethod === 'paypal' && (
            <PayPalPaymentModal
              isOpen={showPaymentModal}
              bookingId={booking.id}
              amount={depositAmount}
              currency={currency || 'USD'}
              onSuccess={handlePaymentSuccess}
              onClose={handlePaymentClose}
            />
          )}
        </>
      )}

      {/* Cancel Booking Modal */}
      {showCancelModal && booking && (
        <CancelBookingModal
          isOpen={showCancelModal}
          booking={booking}
          onClose={() => setShowCancelModal(false)}
          onSuccess={handleCancelSuccess}
        />
      )}
    </>
  );
};

export default DepositPaymentModal;

