import React, { useContext, useState, useRef, useEffect } from 'react' import useSWR from 'swr' import { WizardContext } from '../context/wizardStore' import { DateUtils } from 'react-day-picker' import DayPickerInput from 'react-day-picker/DayPickerInput' import Required from './required' import { dateFormatBackend } from '../helpers/date' import { getNextSmaller, getNextBigger } from '../helpers/array' import MomentLocaleUtils, { formatDate, parseDate, } from 'react-day-picker/moment' import 'moment/locale/de' const fetcher = (path) => fetch(path).then((r) => r.json()) export default function DateSelect() { const { state, onChange } = useContext(WizardContext) const [range, setRange] = useState({ form: state.startDate && new Date(state.startDate), to: state.endDate && new Date(state.endDate), }) const { from, to } = range const { data: daysBooked, error: fetchBookedOnError } = useSWR( '/api/daysbooked', fetcher ) const prevBookedDay = getNextSmaller( daysBooked, dateFormatBackend(from || to) ) const nextBookedDay = getNextBigger(daysBooked, dateFormatBackend(from || to)) const fromRef = useRef() const toRef = useRef() function dayBooked(day) { return daysBooked && daysBooked.includes(dateFormatBackend(day)) } function dayDisabled(day) { return ( DateUtils.isPastDay(day) || dayBooked(day) || (prevBookedDay && day < new Date(prevBookedDay)) || (nextBookedDay && day > new Date(nextBookedDay)) || day < from ) } useEffect(() => { toRef.current?.getInput().focus() }, [from]) useEffect(() => { onChange({ startDate: from?.toISOString(), endDate: to?.toISOString() }) }, [from, to]) const disabledDays = [dayDisabled] const modifiers = { dayBooked, start: from, end: to, } if (fetchBookedOnError) { return (
Entschuldige, aber die Buchungszeiten konnten nicht geladen werden. Versuchen Sie es später nochmals.
) } return (
setRange({ ...range, from })} /> {' - '} setRange({ ...range, to })} />
) }