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

export const getServerSideProps = getServerSideBooking

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

export default function ShowBooking({
  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 onCancelBooking = async () => {
    if (!confirm('Soll die Buchung wirklich storniert werden?')) {
      return
    }

    try {
      setStoringBookingError(null)
      setStoringBooking(true)
      const updatedBooking = await cancelBooking(booking)
      setBooking(updatedBooking)
    } catch (error) {
      setStoringBookingError(
        'Buchung konnte nicht storniert werden. Schreiben Sie uns eine E-Mail!'
      )
      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">Ihre Buchung</h2>
        <div>
          <strong>Buchungsstatus:</strong> {getBookingStatus(booking.status)}
        </div>
        <div>
          <strong>Buchungszeitraum:</strong>{' '}
          {dateFormatFrontend(new Date(booking.startDate))} -{' '}
          {dateFormatFrontend(new Date(booking.endDate))}
        </div>
        {storingBookingError && (
          <div className="error-message flex-grow">{storingBookingError}</div>
        )}
        {[BOOKING_STATUS.CONFIRMED, BOOKING_STATUS.REQUESTED].includes(
          booking.status
        ) && (
          <div className="my-6">
            <button
              onClick={onCancelBooking}
              className="btn btn-red"
              disabled={storingBooking}
            >
              Buchung Stornieren
            </button>
          </div>
        )}
      </main>

      <Footer />
    </div>
  )
}
