import React, { useContext, useState, useRef, useEffect } from 'react' import useSWR from 'swr' import { WizardContext } from '../context/wizardStore' import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button' import { DateUtils } from 'react-day-picker' import DayPickerInput from 'react-day-picker/DayPickerInput' import Required from './required' import { dateFormat } from '../helpers/date' import { getNextSmaller, getNextBigger } from '../helpers/array' const fetcher = (path) => fetch(path).then((r) => r.json()) export default function DateSelect() { const { state, onChange } = useContext(WizardContext) const [range, setRange] = useState({ form: null, to: null }) const { data: daysBooked, error: fetchBookedOnError } = useSWR( '/api/daysbooked', fetcher ) const prevBookedDay = getNextSmaller( daysBooked, dateFormat(range.from || range.to) ) const nextBookedDay = getNextBigger( daysBooked, dateFormat(range.from || range.to) ) const fromRef = useRef() const toRef = useRef() function dayBooked(day) { return daysBooked && daysBooked.includes(dateFormat(day)) } function dayDisabled(day) { return ( DateUtils.isPastDay(day) || dayBooked(day) || (prevBookedDay && day < new Date(prevBookedDay)) || (nextBookedDay && day > new Date(nextBookedDay)) ) } function parseDate(value) { return new Date(value) } useEffect(() => { toRef.current?.getInput().focus() }, [range.from]) const { from, to } = range const disabledDays = [dayDisabled] const modifiers = { dayBooked, start: from, end: to, } if (fetchBookedOnError) { return (