import { useEffect, useState } from 'react'; import { reservationsService } from '@/features/reservations/services/reservationsService'; import { Reservation } from '@/features/reservations/types'; import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; function getToday(): string { return new Date().toISOString().slice(0, 10); } function normalizeDateInput(value: string): string { const digits = value.replace(/\D/g, '').slice(0, 8); if (digits.length <= 4) { return digits; } if (digits.length <= 6) { return `${digits.slice(0, 4)}-${digits.slice(4)}`; } return `${digits.slice(0, 4)}-${digits.slice(4, 6)}-${digits.slice(6)}`; } export function useOfficeAvailability(officeId?: string) { const [selectedDate, setSelectedDateValue] = useState(getToday); const [reservations, setReservations] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const loadAvailability = async () => { if (!officeId) { setReservations([]); setLoading(false); setError('No se indicó una oficina válida'); return; } if (selectedDate.trim().length !== 10) { setReservations([]); setLoading(false); return; } try { setError(null); setLoading(true); const data = await reservationsService.getByOfficeAndDate(officeId, selectedDate); setReservations(data); } catch (err) { setError(getErrorMessage(err, 'No se pudo cargar la disponibilidad')); } finally { setLoading(false); } }; useEffect(() => { loadAvailability(); }, [officeId, selectedDate]); const setSelectedDate = (value: string) => { setError(null); setSelectedDateValue(normalizeDateInput(value)); }; return { selectedDate, reservations, loading, error, setSelectedDate, reload: loadAvailability, }; }