import React, { useContext } from 'react' import classnames from 'classnames' import { isPast, isSameDay, isAfter, isWithinInterval } from 'date-fns' import useSWR from 'swr' import Calendar, { DateCallback } from 'react-calendar' import { dateFormatBackend } from '../../helpers/date' import { WizardContext } from './context/wizardStore' const fetcher = (path: string) => fetch(path).then((r) => r.json()) export default function MyCalendar() { const { onChange, state } = useContext(WizardContext) const { startDate: start, endDate: end } = state.formData const startDate = (start && new Date(start)) || null const endDate = (end && new Date(end)) || null const { data: daysBooked, error: fetchBookedOnError } = useSWR( '/api/daysbooked', fetcher ) function tileClassName({ date, view }) { const isMonthView = view === 'month' const isDaysBookedLoaded = !!daysBooked const isInPast = isPast(date) const isBooked = daysBooked?.includes(dateFormatBackend(date)) return classnames({ 'react-calendar__tile--past': isInPast, 'react-calendar__tile--booked': isMonthView && isDaysBookedLoaded && isBooked && !isInPast, 'react-calendar__tile--free': isMonthView && isDaysBookedLoaded && !isBooked && !isInPast, 'react-calendar__tile--selected': (startDate && isWithinInterval(date, { start: startDate, end: endDate || startDate, })) || isSameDay(date, startDate), }) } if (fetchBookedOnError) { return (