'use client' import { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { CheckCircle2, Calendar, Clock, MapPin, CreditCard } from 'lucide-react' import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js' import { format } from 'date-fns' import { es } from 'date-fns/locale' import { useAuth } from '@/lib/auth/context' export default function CitaPage() { const { user, loading: authLoading } = useAuth() const router = useRouter() const [formData, setFormData] = useState({ nombre: '', email: '', telefono: '', notas: '' }) const [bookingDetails, setBookingDetails] = useState(null) const [pageLoading, setPageLoading] = useState(false) const [submitted, setSubmitted] = useState(false) const [paymentIntent, setPaymentIntent] = useState(null) const [showPayment, setShowPayment] = useState(false) const stripe = useStripe() const elements = useElements() useEffect(() => { if (!authLoading && !user) { router.push('/booking/login?redirect=/booking/cita' + window.location.search) } }, [user, authLoading, router]) if (authLoading) { return (

Cargando...

) } if (!user) { return null } useEffect(() => { const params = new URLSearchParams(window.location.search) const service_id = params.get('service_id') const location_id = params.get('location_id') const date = params.get('date') const time = params.get('time') if (service_id && location_id && date && time) { fetchBookingDetails(service_id, location_id, date, time) } }, []) useEffect(() => { if (user) { setFormData(prev => ({ ...prev, email: user.email || '' })) } }, [user]) const fetchBookingDetails = async (serviceId: string, locationId: string, date: string, time: string) => { try { const response = await fetch(`/api/availability/time-slots?location_id=${locationId}&service_id=${serviceId}&date=${date}`) const data = await response.json() setBookingDetails({ service_id: serviceId, location_id: locationId, date: date, time: time, startTime: `${date}T${time}` }) } catch (error) { console.error('Error fetching booking details:', error) } } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setPageLoading(true) try { const response = await fetch('/api/create-payment-intent', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ customer_email: formData.email, customer_phone: formData.telefono, customer_first_name: formData.nombre.split(' ')[0] || formData.nombre, customer_last_name: formData.nombre.split(' ').slice(1).join(' '), service_id: bookingDetails.service_id, location_id: bookingDetails.location_id, start_time_utc: bookingDetails.startTime, notes: formData.notas }) }) const data = await response.json() if (response.ok) { setPaymentIntent(data) setShowPayment(true) } else { alert('Error al preparar el pago: ' + (data.error || 'Error desconocido')) } } catch (error) { console.error('Error creating payment intent:', error) alert('Error al preparar el pago') } finally { setPageLoading(false) } } const handleChange = (e: React.ChangeEvent) => { setFormData({ ...formData, [e.target.name]: e.target.value }) } const handlePayment = async () => { if (!stripe || !elements) return setPageLoading(true) const { error } = await stripe.confirmCardPayment(paymentIntent.clientSecret, { payment_method: { card: elements.getElement(CardElement)!, } }) if (error) { alert('Error en el pago: ' + error.message) setPageLoading(false) } else { // Payment succeeded, create booking try { const response = await fetch('/api/bookings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ customer_email: formData.email, customer_phone: formData.telefono, customer_first_name: formData.nombre.split(' ')[0] || formData.nombre, customer_last_name: formData.nombre.split(' ').slice(1).join(' '), service_id: bookingDetails.service_id, location_id: bookingDetails.location_id, start_time_utc: bookingDetails.startTime, notes: formData.notas, payment_intent_id: paymentIntent.id }) }) const data = await response.json() if (response.ok && data.success) { setSubmitted(true) } else { alert('Error al crear la reserva: ' + (data.error || 'Error desconocido')) } } catch (error) { console.error('Error creating booking:', error) alert('Error al crear la reserva') } finally { setPageLoading(false) } } } if (submitted) { return (

¡Reserva Confirmada!

Hemos enviado un correo de confirmación con los detalles de tu cita.

Fecha: {format(new Date(bookingDetails.date), 'PPP', { locale: es })}

Hora: {bookingDetails.time}

Puedes agregar esta cita a tu calendario.

) } if (!bookingDetails) { return (

Cargando detalles de la reserva...

) } return (
Resumen de la Cita

Fecha

{format(new Date(bookingDetails.date), 'PPP', { locale: es })}

Hora

{bookingDetails.time}

Ubicación

Anchor:23 - Saltillo

Tus Datos Ingresa tus datos personales para completar la reserva