import { GetServerSideProps } from 'next'
import React, { useEffect, useState } from 'react'
import Footer from '../../../components/footer'
import Header from '../../../components/header'
import Input from '../../../components/wizard/input'
import { BookingDocument } from '../../../db/booking'
import { BOOKING_STATUS, MILAGE_RATES } 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)

  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 Bill({
  booking: bookingProp,
}: {
  booking: BookingDocument
}) {
  const [booking, setBooking] = useState(bookingProp)
  const [milageStart, setMilageStart] = useState(0)
  const [milageEnd, setMilageEnd] = useState(0)
  const [rate, setRate] = useState(MILAGE_RATES.EXTERN_UP_TO_200)
  const milage =
    (0 < milageEnd &&
      0 < milageStart &&
      milageStart < milageEnd &&
      milageEnd - milageStart) ||
    0
  const total = milage && rate && milage * rate

  // 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. Kontaktieren Sie uns bitt per E-Mail!'
      )
    }
  }

  return (
    <div className="mx-3 flex flex-col min-h-screen">
      <Header />
      <main className="flex-grow">
        <h2 className="text-3xl">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>
        <div>
          <strong>Bucher:</strong> {booking.booker.name}
        </div>
        <div>
          <Input
            label="Anfangskilometer"
            name="milageStart"
            required
            value={milageStart}
            type="number"
            onChange={(e: React.ChangeEvent<React.ElementRef<'input'>>) =>
              setMilageStart(Number(e.target.value))
            }
          />
          <Input
            label="Endkilometer"
            name="milageEnd"
            required
            value={milageEnd}
            type="number"
            onChange={(e: React.ChangeEvent<React.ElementRef<'input'>>) =>
              setMilageEnd(Number(e.target.value))
            }
          />
          <Input label="Gefahren" name="milage" readOnly value={milage} />
          <div className="fsw">
            <div className="fs">
              <label className="flabel">Rate</label>
              <div className="relative">
                <select
                  className="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
                  id="rate"
                  onChange={(
                    e: React.ChangeEvent<React.ElementRef<'select'>>
                  ) => setRate(Number(e.target.value))}
                >
                  <option value={MILAGE_RATES.INTERN_UP_TO_200}>
                    Intern bis 200 ({MILAGE_RATES.INTERN_UP_TO_200})
                  </option>
                  <option value={MILAGE_RATES.INTERN_200_1000}>
                    Intern 200-1000 ({MILAGE_RATES.INTERN_200_1000})
                  </option>
                  <option value={MILAGE_RATES.INTERN_1001_2000}>
                    Intern 1001-2000 ({MILAGE_RATES.INTERN_1001_2000})
                  </option>
                  <option value={MILAGE_RATES.INTERN_OVER_2000}>
                    Intern ab 2001 ({MILAGE_RATES.INTERN_OVER_2000})
                  </option>
                  <option value={MILAGE_RATES.EXTERN_UP_TO_200}>
                    Extern bis 200 ({MILAGE_RATES.EXTERN_UP_TO_200})
                  </option>
                  <option value={MILAGE_RATES.EXTERN_200_1000}>
                    Extern 200-1000 ({MILAGE_RATES.EXTERN_200_1000})
                  </option>
                  <option value={MILAGE_RATES.EXTERN_1001_2000}>
                    Extern 1001-2000 ({MILAGE_RATES.EXTERN_1001_2000})
                  </option>
                  <option value={MILAGE_RATES.EXTERN_OVER_2000}>
                    Extern ab 2001 ({MILAGE_RATES.EXTERN_OVER_2000})
                  </option>
                </select>
                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                  <svg
                    className="fill-current h-4 w-4"
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 20 20"
                  >
                    <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
                  </svg>
                </div>
              </div>
            </div>
          </div>

          <Input label="Summe" name="milage" readOnly value={total} />
        </div>
        <button onClick={onCancelBooking} className="btn btn-blue">
          Rechnung Erstellen
        </button>
      </main>

      <Footer />
    </div>
  )
}
