import React, { useState, useEffect } from 'react'; import { createPayPalOrder } from '../../services/api/paymentService'; import { Loader2, AlertCircle } from 'lucide-react'; interface PayPalPaymentWrapperProps { bookingId: number; amount: number; currency?: string; onError?: (error: string) => void; } const PayPalPaymentWrapper: React.FC = ({ bookingId, amount, currency = 'USD', onError, }) => { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [approvalUrl, setApprovalUrl] = useState(null); // Initialize PayPal order useEffect(() => { const initializePayPal = async () => { try { setLoading(true); setError(null); // Get current URL for return/cancel URLs 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); if (onError) { onError(errorMessage); } } finally { setLoading(false); } }; initializePayPal(); }, [bookingId, amount, currency, onError]); const handlePayPalClick = () => { if (approvalUrl) { // Redirect to PayPal approval page window.location.href = approvalUrl; } }; if (loading) { return (
Initializing PayPal payment...
); } if (error) { return (

Payment Initialization Failed

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

); } if (!approvalUrl) { return (
Loading PayPal...
); } return (

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

); }; export default PayPalPaymentWrapper;