import React from 'react'
import classnames from 'classnames'
import { isPast } from 'date-fns'
import useSWR from 'swr'
import Calendar from 'react-calendar'
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
  )

  function tileClassName({ date, view }) {
    const isMonthView = view === 'month'
    const isDaysBookedLoaded = !!daysBooked
    const isBooked = daysBooked?.includes(dateFormatBackend(date))
    return classnames({
      'react-calendar__tile--past': isPast(date),
      'react-calendar__tile--booked':
        isMonthView && isDaysBookedLoaded && isBooked,
      'react-calendar__tile--free':
        isMonthView && isDaysBookedLoaded && !isBooked,
    })
  }

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

  return (
    <div className="mb-12 p-6 bg-blue-100 rounded">
      <h2 className="text-xl">Buchungsübersicht</h2>
      <Calendar minDate={new Date()} tileClassName={tileClassName} />
      <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>
  )
}
