import { GetServerSideProps } from 'next'
import React, { useEffect, useState } from 'react'
import Footer from '../../../components/footer'
import Header from '../../../components/header'
import { BookingDocument } from '../../../db/booking'
import { BOOKING_STATUS } from '../../../db/enums'
import { getBookingByUUID } from '../../../db/index'
import { dateFormatFrontend } from '../../../helpers/date'

export const getServerSideProps: GetServerSideProps = async (context) => {
  const {
    res,
    params: { uuid: uuids },
  } = context
  const uuid = Array.isArray(uuids) ? uuids[0] : uuids
  const booking = await getBookingByUUID(uuid)
  await booking.populate('booker').execPopulate()

  if (!booking) {
    res.statusCode = 404
    res.end()
    return { props: {} }
  }

  // TODO: hack, not sure why _id is not serilizable
  const bookingJSON = JSON.parse(JSON.stringify(booking.toJSON()))
  return {
    props: { booking: bookingJSON },
  }
}

function getBookingStatus(booking: BookingDocument) {
  switch (booking.status) {
    case BOOKING_STATUS.REQUESTED:
      return 'In Bearbeitung'
    case BOOKING_STATUS.CONFIRMED:
      return 'BestÃ¤tigt'
    case BOOKING_STATUS.REJECTED:
      return 'Abgewiesen'
    case BOOKING_STATUS.CANCELED:
      return 'Storniert'
    default:
      return 'Unbekannt - bitte kontaktieren Sie uns!'
  }
}

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)

  // 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 {
      const updatedBooking = await cancelBooking(booking)
      setBooking(updatedBooking)
    } catch (e) {
      alert(
        'Die Buchung konnte nicht storniert werden. Schreiben Sie uns eine E-Mail'
      )
    }
  }

  return (
    <div className="mx-3 flex flex-col min-h-screen">
      <Header />
      <main className="flex-grow">
        <h2 className="text-3xl">Ihre Pfadi Bussle Buchung</h2>
        <div>
          <strong>Buchungsstatus:</strong> {getBookingStatus(booking)}
        </div>
        <div>
          <strong>Buchungszeitraum:</strong>{' '}
          {dateFormatFrontend(new Date(booking.startDate))} -{' '}
          {dateFormatFrontend(new Date(booking.endDate))}
        </div>
        {[BOOKING_STATUS.CONFIRMED, BOOKING_STATUS.REQUESTED].includes(
          booking.status
        ) && (
          <div className="my-6">
            <button onClick={onCancelBooking} className="btn btn-red">
              Buchung Stornieren
            </button>
          </div>
        )}
      </main>

      <Footer />
    </div>
  )
}
