import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useCart } from '@/contexts/CartContext'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Textarea } from '@/components/ui/textarea'; import { Separator } from '@/components/ui/separator'; import { Badge } from '@/components/ui/badge'; import { ArrowLeft, CreditCard, Smartphone, Building, Truck, Shield, Check, X, Loader2 } from 'lucide-react'; import Header from '@/components/Header'; import Footer from '@/components/Footer'; import { useToast } from '@/hooks/use-toast'; import { useBooking } from '@/hooks/useBooking'; import { useStripe } from '@/hooks/useStripe'; import { paymentService } from '@/services/paymentService'; interface CustomerInfo { firstName: string; lastName: string; email: string; phone: string; address: string; city: string; country: string; zipCode: string; } interface PaymentInfo { method: 'credit_card' | 'paypal' | 'bank_transfer' | 'cash'; cardNumber: string; expiryDate: string; cvv: string; cardName: string; } const Checkout = () => { const navigate = useNavigate(); const { items, getTotalPrice, clearCart } = useCart(); const { toast } = useToast(); const { createBooking } = useBooking(); const { stripe, credentials, loading: stripeLoading } = useStripe(); const [step, setStep] = useState(1); const [isProcessing, setIsProcessing] = useState(false); const [customerInfo, setCustomerInfo] = useState({ firstName: '', lastName: '', email: '', phone: '', address: '', city: '', country: 'Dominican Republic', zipCode: '' }); const [paymentInfo, setPaymentInfo] = useState({ method: 'credit_card', cardNumber: '', expiryDate: '', cvv: '', cardName: '' }); const [specialRequests, setSpecialRequests] = useState(''); if (items.length === 0) { return (

Tu carrito está vacío

Agrega algunas ofertas a tu carrito para continuar.

); } const totalPrice = getTotalPrice(); const taxes = totalPrice * 0.18; // 18% ITBIS (impuesto dominicano) const serviceFee = totalPrice * 0.05; // 5% fee de servicio const finalTotal = totalPrice + taxes + serviceFee; const paymentMethods = [ { id: 'credit_card', name: 'Tarjeta de Crédito/Débito', icon: CreditCard }, { id: 'paypal', name: 'PayPal', icon: Smartphone }, { id: 'bank_transfer', name: 'Transferencia Bancaria', icon: Building }, { id: 'cash', name: 'Pago en Efectivo', icon: Truck } ]; const handleCustomerInfoChange = (field: keyof CustomerInfo, value: string) => { setCustomerInfo(prev => ({ ...prev, [field]: value })); }; const handlePaymentInfoChange = (field: keyof PaymentInfo, value: string) => { setPaymentInfo(prev => ({ ...prev, [field]: value })); }; const saveOrderToJSON = (orderData: any) => { const orders = JSON.parse(localStorage.getItem('karibeo_orders') || '[]'); orders.push(orderData); localStorage.setItem('karibeo_orders', JSON.stringify(orders)); }; const processPayment = async () => { setIsProcessing(true); try { // Si el método de pago es tarjeta de crédito y Stripe está disponible if (paymentInfo.method === 'credit_card' && stripe && credentials) { // Crear PaymentIntent desde el backend const paymentIntent = await paymentService.createPaymentIntent({ amount: Math.round(finalTotal * 100), // Convertir a centavos currency: 'usd', description: `Reserva de ${items.length} item(s)`, metadata: { customerName: `${customerInfo.firstName} ${customerInfo.lastName}`, customerEmail: customerInfo.email, }, }); // En un entorno real, aquí se confirmaría el pago con Stripe Elements // Por ahora, simulamos que el pago fue exitoso console.log('Payment Intent created:', paymentIntent); } // Create reservations for each cart item const reservationPromises = items.map(async (item) => { const checkInDate = item.selectedDate ? new Date(item.selectedDate) : new Date(); // Add time slot if available if (item.timeSlot) { const [hours, minutes] = item.timeSlot.split(':'); checkInDate.setHours(parseInt(hours), parseInt(minutes), 0, 0); } const bookingData = { listingId: item.id, guestName: `${customerInfo.firstName} ${customerInfo.lastName}`, guestEmail: customerInfo.email, guestPhone: customerInfo.phone, checkIn: checkInDate.toISOString(), guests: item.guests || 1, totalAmount: item.price * (item.guests || 1), specialRequests: specialRequests, }; return await createBooking(bookingData); }); const results = await Promise.all(reservationPromises); // Check if all reservations were created successfully const allSuccess = results.every(result => result.success); if (!allSuccess) { throw new Error('Some reservations failed to create'); } // Simulate payment processing await new Promise(resolve => setTimeout(resolve, 2000)); const orderData = { id: Date.now().toString(), date: new Date().toISOString(), items: items, customerInfo, paymentInfo: { method: paymentInfo.method, cardLast4: paymentInfo.method === 'credit_card' ? paymentInfo.cardNumber.slice(-4) : undefined }, specialRequests, pricing: { subtotal: totalPrice, taxes, serviceFee, total: finalTotal }, status: 'confirmed', reservations: results.map(r => r.data), stripeEnabled: !!credentials?.enabled, }; saveOrderToJSON(orderData); clearCart(); toast({ title: "¡Pago procesado exitosamente!", description: "Tus reservas han sido confirmadas. Recibirás un email de confirmación.", }); navigate('/order-confirmation', { state: { orderData } }); } catch (error) { console.error('Payment error:', error); toast({ title: "Error al procesar el pago", description: "Hubo un problema al procesar tu reserva. Por favor intenta nuevamente.", variant: "destructive", }); } finally { setIsProcessing(false); } }; const validateStep1 = () => { return customerInfo.firstName && customerInfo.lastName && customerInfo.email && customerInfo.phone; }; const validateStep2 = () => { if (paymentInfo.method === 'credit_card') { return paymentInfo.cardNumber && paymentInfo.expiryDate && paymentInfo.cvv && paymentInfo.cardName; } return true; }; return (

Checkout

{/* Progress Steps */}
= 1 ? 'text-primary' : 'text-gray-400'}`}>
= 1 ? 'border-primary bg-primary text-white' : 'border-gray-300' }`}> {step > 1 ? : '1'}
Información Personal
1 ? 'bg-primary' : 'bg-gray-300'}`} />
= 2 ? 'text-primary' : 'text-gray-400'}`}>
= 2 ? 'border-primary bg-primary text-white' : 'border-gray-300' }`}> {step > 2 ? : '2'}
Pago
2 ? 'bg-primary' : 'bg-gray-300'}`} />
= 3 ? 'text-primary' : 'text-gray-400'}`}>
= 3 ? 'border-primary bg-primary text-white' : 'border-gray-300' }`}> 3
Confirmación
{/* Main Content */}
{step === 1 && ( Información Personal
handleCustomerInfoChange('firstName', e.target.value)} placeholder="Tu nombre" />
handleCustomerInfoChange('lastName', e.target.value)} placeholder="Tu apellido" />
handleCustomerInfoChange('email', e.target.value)} placeholder="tu@email.com" />
handleCustomerInfoChange('phone', e.target.value)} placeholder="+1 (809) 123-4567" />
handleCustomerInfoChange('address', e.target.value)} placeholder="Calle, número, sector" />
handleCustomerInfoChange('city', e.target.value)} placeholder="Santo Domingo" />
handleCustomerInfoChange('zipCode', e.target.value)} placeholder="10001" />