'use client' import { useState, useEffect } from 'react' import { useRouter, useSearchParams } 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, Mail, Phone, Search, User } from 'lucide-react' import { format, parseISO } from 'date-fns' import { es } from 'date-fns/locale' import MockPaymentForm from '@/components/booking/mock-payment-form' export default function CitaPage() { const router = useRouter() const searchParams = useSearchParams() const [step, setStep] = useState<'search' | 'details' | 'payment' | 'success'>('search') const [searchValue, setSearchValue] = useState('') const [searchType, setSearchType] = useState<'email' | 'phone'>('email') const [customer, setCustomer] = useState(null) const [searchingCustomer, setSearchingCustomer] = useState(false) const [formData, setFormData] = useState({ nombre: '', email: '', telefono: '', notas: '' }) const [bookingDetails, setBookingDetails] = useState(null) const [pageLoading, setPageLoading] = useState(false) const [submitted, setSubmitted] = useState(false) const [showPayment, setShowPayment] = useState(false) const [depositAmount, setDepositAmount] = useState(0) const [errors, setErrors] = useState>({}) useEffect(() => { const service_id = searchParams.get('service_id') const location_id = searchParams.get('location_id') const date = searchParams.get('date') const time = searchParams.get('time') const customer_id = searchParams.get('customer_id') if (service_id && location_id && date && time) { fetchBookingDetails(service_id, location_id, date, time) } if (customer_id) { fetchCustomerById(customer_id) } }, [searchParams]) const fetchCustomerById = async (customerId: string) => { try { const response = await fetch(`/api/customers?email=${customerId}`) const data = await response.json() if (data.exists && data.customer) { setCustomer(data.customer) setFormData(prev => ({ ...prev, nombre: `${data.customer.first_name} ${data.customer.last_name}`, email: data.customer.email, telefono: data.customer.phone || '' })) setStep('details') } } catch (error) { console.error('Error fetching customer:', error) } } 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() if (data.availability?.services) { const service = data.availability.services[0] const deposit = Math.min(service.base_price * 0.5, 200) setDepositAmount(deposit) } setBookingDetails({ service_id: serviceId, location_id: locationId, date: date, time: time, startTime: `${date}T${time}` }) } catch (error) { console.error('Error fetching booking details:', error) setErrors({ fetch: 'Error al cargar los detalles de la reserva' }) } } const handleSearchCustomer = async (e: React.FormEvent) => { e.preventDefault() setSearchingCustomer(true) setErrors({}) if (!searchValue.trim()) { setErrors({ search: 'Ingresa un email o teléfono' }) setSearchingCustomer(false) return } try { const response = await fetch(`/api/customers?${searchType}=${encodeURIComponent(searchValue)}`) const data = await response.json() if (data.exists && data.customer) { setCustomer(data.customer) setFormData(prev => ({ ...prev, nombre: `${data.customer.first_name} ${data.customer.last_name}`, email: data.customer.email, telefono: data.customer.phone || '' })) setStep('details') } else { const params = new URLSearchParams({ ...Object.fromEntries(searchParams.entries()), [searchType]: searchValue }) router.push(`/booking/registro?${params.toString()}`) } } catch (error) { console.error('Error searching customer:', error) setErrors({ search: 'Error al buscar cliente' }) } finally { setSearchingCustomer(false) } } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setErrors({}) setPageLoading(true) const validationErrors: Record = {} if (!formData.nombre.trim()) { validationErrors.nombre = 'Nombre requerido' } if (!formData.email.trim() || !formData.email.includes('@')) { validationErrors.email = 'Email inválido' } if (!formData.telefono.trim()) { validationErrors.telefono = 'Teléfono requerido' } if (Object.keys(validationErrors).length > 0) { setErrors(validationErrors) setPageLoading(false) return } setShowPayment(true) setPageLoading(false) } const handleChange = (e: React.ChangeEvent) => { setFormData({ ...formData, [e.target.name]: e.target.value }) setErrors({ ...errors, [e.target.name]: '' }) } const handleMockPayment = async (paymentMethod: any) => { setPageLoading(true) try { const response = await fetch('/api/bookings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ customer_id: customer?.id, 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_method_id: 'mock_' + paymentMethod.cardNumber.slice(-4), deposit_amount: depositAmount }) }) const data = await response.json() if (response.ok && data.success) { setSubmitted(true) } else { setErrors({ submit: data.error || 'Error al crear la reserva' }) setPageLoading(false) } } catch (error) { console.error('Error creating booking:', error) setErrors({ submit: 'Error al crear la reserva' }) 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}

Depósito pagado: ${depositAmount.toFixed(2)} USD

) } if (!bookingDetails) { return (

Cargando detalles de la reserva...

) } return (
{step === 'search' && (
Buscar Cliente Ingresa tu email o teléfono para continuar con la reserva
setSearchValue(e.target.value)} className="pl-10" style={{ borderColor: errors.search ? '#ef4444' : 'var(--mocha-taupe)' }} placeholder={searchType === 'email' ? 'tu@email.com' : '+52 844 123 4567'} />
{errors.search &&

{errors.search}

}
{customer && (

Cliente encontrado:

{customer.first_name} {customer.last_name}

{customer.email}

)}
)} {step === 'details' && (
Resumen de la Cita

Fecha

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

Hora

{format(parseISO(bookingDetails.time), 'HH:mm', { locale: es })}

Ubicación

Anchor:23 - Saltillo

{customer && (

Cliente

{customer.first_name} {customer.last_name}

)}
{showPayment && ( Pago del Depósito

Se requiere un depósito del 50% del servicio (máximo $200) para confirmar tu reserva.

)}
Tus Datos {customer ? 'Verifica y confirma tus datos' : 'Ingresa tus datos personales para completar la reserva'} {showPayment ? (
Datos completados. Por favor completa el pago para confirmar.
) : (
{errors.nombre &&

{errors.nombre}

}
{errors.email &&

{errors.email}

}
{errors.telefono &&

{errors.telefono}

}