import React, { useState, useEffect } from 'react'; import { createPayPalOrder } from '../services/paymentService'; import { X, Loader2, AlertCircle } from 'lucide-react'; import { toast } from 'react-toastify'; import { useFormatCurrency } from '../hooks/useFormatCurrency'; interface PayPalPaymentModalProps { isOpen: boolean; bookingId: number; amount: number; currency?: string; onSuccess: () => void; onClose: () => void; } const PayPalPaymentModal: React.FC = ({ isOpen, bookingId, amount, currency: propCurrency, onSuccess: _onSuccess, onClose, }) => { const { currency: contextCurrency } = useFormatCurrency(); const currency = propCurrency || contextCurrency || 'USD'; const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [approvalUrl, setApprovalUrl] = useState(null); useEffect(() => { if (!isOpen) return; const initializePayPal = async () => { try { setLoading(true); setError(null); const currentUrl = window.location.origin; const returnUrl = `${currentUrl}/payment/paypal/return?bookingId=${bookingId}`; const cancelUrl = `${currentUrl}/payment/paypal/cancel?bookingId=${bookingId}`; const response = await createPayPalOrder( bookingId, amount, currency, returnUrl, cancelUrl ); if (response.success && response.data) { const { approval_url } = response.data; if (!approval_url) { throw new Error('Approval URL not received from server'); } setApprovalUrl(approval_url); } else { throw new Error(response.message || 'Failed to initialize PayPal payment'); } } catch (err: any) { console.error('Error initializing PayPal:', err); const errorMessage = err.response?.data?.message || err.message || 'Failed to initialize PayPal payment'; setError(errorMessage); toast.error(errorMessage); } finally { setLoading(false); } }; initializePayPal(); }, [isOpen, bookingId, amount, currency]); const handlePayPalClick = () => { if (approvalUrl) { window.location.href = approvalUrl; } }; if (!isOpen) return null; return (
{/* Header */}

PayPal Payment

{/* Content */}
{loading ? (

Initializing PayPal payment...

) : error ? (

Payment Initialization Failed

{error || 'Unable to initialize PayPal payment. Please try again.'}

) : approvalUrl ? (

Complete Payment with PayPal

You will be redirected to PayPal to securely complete your payment of{' '} {new Intl.NumberFormat('en-US', { style: 'currency', currency: currency, }).format(amount)}

Secure payment powered by PayPal

) : (

Loading PayPal...

)}
); }; export default PayPalPaymentModal;