import React, { useState } from 'react'
import classnames from 'classnames'
import useSWR from 'swr'
import moment, { 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 (
    <div className="mb-12">
      <h2 className="text-xl">Buchungsübersicht</h2>
      <Calendar
        onChangeMonth={(date: React.SetStateAction<Moment>) => setDate(date)}
        date={date}
        renderDay={({
          day,
          classNames,
          onPickDate,
        }: {
          day: Moment
          classNames: string
          onPickDate: any
        }) => (
          <div
            key={day.format()}
            className={classnames(
              'Calendar-grid-item',
              day.isSame(moment(), 'day') && 'Calendar-grid-item--current',
              day.isBefore(moment(), 'day') && 'Calendar-grid-item--past',
              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={() => {}}
      />
      <div className="mt-6 flex justify-center">
        <div>
          <div className="inline-block w-5 h-5 bg-green-200 rounded align-text-bottom"></div>
          <span className="ml-2">Frei</span>
        </div>
        <div>
          <div className="ml-6 inline-block w-5 h-5 bg-red-200 rounded align-text-bottom"></div>
          <span className="ml-2">Belegt</span>
        </div>
      </div>
    </div>
  )
}
