import React, { useEffect, useState } from 'react'
import { getServerSideBooking } from '../../../lib/getServerSideProps'
import { IBooking } from '../../../db/booking'
import { BOOKING_STATUS } from '../../../db/enums'
import { daysFormatFrontend } from '../../../helpers/date'
import { log } from '../../../helpers/log'
import { getBookingStatus, cancelBooking } from '../../../helpers/booking'
import Layout from '../../../components/layout'

export const getServerSideProps = getServerSideBooking

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

    try {
      setStoringBookingError(null)
      setStoringBooking(true)
      const updatedBooking = await cancelBooking(booking.uuid)
      setBooking(updatedBooking)
    } catch (error) {
      setStoringBookingError(
        'Buchung konnte nicht storniert werden. Schreiben Sie uns eine E-Mail!'
      )
      log.error('Failed to store booking', error)
    }
    setStoringBooking(false)
  }

  return (
    <Layout>
      <div>
        <strong>Buchungsstatus:</strong> {getBookingStatus(booking.status)}
      </div>
      <div>
        <strong>Buchungszeitraum:</strong> {daysFormatFrontend(booking.days)}
      </div>
      {storingBookingError && (
        <div className="error-message 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>
      )}
    </Layout>
  )
}
