import React, { useEffect, useState } from 'react'
import Calendar from '../../../../components/calendar'
import { getServerSideBooking } from '../../../../lib/getServerSideProps'
import { IBooking } from '../../../../db/booking'
import { patchBooking } from '../../../../helpers/booking'
import { log } from '../../../../helpers/log'
import { BOOKING_STATUS } from '../../../../db/enums'
import BookingTable from '../../../../components/bookingTable'
import Layout from '../../../../components/layout'
import withAuth from '../../../../helpers/withAuth'

export const getServerSideProps = getServerSideBooking

function ShowBookingAdmin({ booking: bookingProp }: { booking: IBooking }) {
  const [booking, setBooking] = useState(bookingProp)
  const [storingBooking, setStoringBooking] = useState(false)
  const [storingBookingError, setStoringBookingError] = useState(null)

  // in case the props change, update the internal state
  useEffect(() => setBooking(bookingProp), [bookingProp])

  const patchBookingStatus = async (status: BOOKING_STATUS) => {
    try {
      setStoringBookingError(null)
      setStoringBooking(true)
      const updatedBooking = await patchBooking(booking.uuid, { status })
      setBooking(updatedBooking)
    } catch (error) {
      setStoringBookingError('Buchung konnte nicht gespeichert werden.')
      log.error('Failed to store booking', error)
    }
    setStoringBooking(false)
  }

  return (
    <Layout>
      <h2 className="text-3xl">Buchung {booking.uuid}</h2>
      <Calendar start={booking.startDate} end={booking.endDate} />
      <BookingTable booking={booking} />
      {storingBookingError && (
        <div className="error-message grow">{storingBookingError}</div>
      )}
      <div className="my-6">
        <button
          onClick={() => patchBookingStatus(BOOKING_STATUS.REQUESTED)}
          className="btn btn-green"
          disabled={storingBooking}
        >
          Zurück auf Requested
        </button>
        <button
          onClick={() => patchBookingStatus(BOOKING_STATUS.CONFIRMED)}
          className="btn btn-blue"
          disabled={storingBooking}
        >
          Buchung Bestätigen
        </button>
        <button
          onClick={() => patchBookingStatus(BOOKING_STATUS.REJECTED)}
          className="btn btn-red"
          disabled={storingBooking}
        >
          Buchung Abweisen
        </button>
      </div>
    </Layout>
  )
}

export default withAuth(ShowBookingAdmin)
