summaryrefslogtreecommitdiffstats
path: root/src/features/reservations/hooks/useOfficeAvailability.ts
blob: 5cdd348ddbd0ef8f486b9abdde7e521cf49af1fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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<Reservation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(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,
  };
}