import React, { useEffect, useState } from 'react'
import Footer from '../../../../components/footer'
import Header from '../../../../components/header'
import Input from '../../../../components/input'
import { getServerSideBooking } from '../../../../lib/getServerSideProps'
import { BookingDocument } from '../../../../db/booking'
import { getBookingStatus } from '../../../../helpers/booking'

export const getServerSideProps = getServerSideBooking

async function storeBooking(booking: BookingDocument) {
  const response = await fetch(`/api/admin/booking/${booking.uuid}`, {
    method: 'PATCH',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
    referrerPolicy: 'no-referrer',
    body: JSON.stringify({ ...booking }),
  })
  return response.json()
}

export default function ShowBookingAdmin({
  booking: bookingProp,
}: {
  booking: BookingDocument
}) {
  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 onStoreBooking = async () => {
    try {
      setStoringBookingError(null)
      setStoringBooking(true)
      const updatedBooking = await storeBooking(booking)
      setBooking(updatedBooking)
    } catch (error) {
      setStoringBookingError('Buchung konnte nicht gespeichert werden.')
      console.error('Failed to store booking', error)
    }
    setStoringBooking(false)
  }

  return (
    <div className="mx-3 flex flex-col min-h-screen">
      <Header />
      <main className="flex-grow">
        <h2 className="text-3xl">Buchung {booking.uuid}</h2>
        <div>
          <strong>Buchungsstatus:</strong> {getBookingStatus(booking)}
        </div>
        <Input label="Von" type="date" value={booking.startDate} readOnly />
        <Input label="Bis" type="date" value={booking.endDate} readOnly />
        {storingBookingError && (
          <div className="error-message flex-grow">{storingBookingError}</div>
        )}
        <div className="my-6">
          <button
            onClick={onStoreBooking}
            className="btn btn-blue"
            disabled={storingBooking}
          >
            Buchung Speichern
          </button>
        </div>
      </main>

      <Footer />
    </div>
  )
}
