import React, { useState } from 'react'
import cx from 'classnames'
import useSWR from 'swr'
import moment from 'moment'
import { Calendar } from 'react-calendar-component'
import { dateFormatBackend } from '../helpers/date'

const fetcher = (path: string) => fetch(path).then((r) => r.json())

export default function MyCalendar() {
  const { data: daysBooked, error: fetchBookedOnError } = useSWR(
    '/api/daysbooked',
    fetcher
  )

  const [date, setDate] = useState(moment())

  function dayBooked(day: Date) {
    return daysBooked && daysBooked.includes(dateFormatBackend(day))
  }

  if (fetchBookedOnError) {
    return (
      <div>
        Entschuldige, aber die Buchungszeiten konnten nicht geladen werden.
        Versuchen Sie es später nochmals.
      </div>
    )
  }

  return (
    <>
      <h2>Buchungsübersicht</h2>
      <Calendar
        onChangeMonth={(date) => setDate(date)}
        date={date}
        renderDay={({ day, classNames, onPickDate }) => (
          <div
            key={day.format()}
            className={cx(
              'Calendar-grid-item',
              day.isSame(moment(), 'day') && 'Calendar-grid-item--current',
              dayBooked(day.toDate()) && 'Calendar-grid-item--booked',
              classNames
            )}
            onClick={(e) => onPickDate(day)}
          >
            {day.format('D')}
          </div>
        )}
        renderHeader={({ date, onPrevMonth, onNextMonth }) => (
          <div className="Calendar-header">
            <button onClick={onPrevMonth}>«</button>
            <div className="Calendar-header-currentDate">
              {date.format('MMMM YYYY')}
            </div>
            <button onClick={onNextMonth}>»</button>
          </div>
        )}
        onPickDate={() => {}}
      />
    </>
  )
}
