<template>
  <q-page padding>
    <q-list>
      <q-form @submit="onSubmit" @reset="onReset" class="q-gutter-md">
        <q-input
          bottom-slots
          v-model="bookingForm.name"
          label="Creating reservation for"
          readonly
        >
          <template v-slot:prepend>
            <q-icon name="person" />
          </template>
        </q-input>
        <q-expansion-item
          expand-separator
          v-model="resourceView"
          icon="calendar_month"
          label="Boat and Time"
          default-opened
          :caption="bookingSummary"
        >
          <q-separator />
          <resource-schedule-viewer-component
            @on-click-time="onClickTime"
            @on-update-duration="
              (value) => {
                bookingForm.duration = value;
              }
            "
          />
          <q-banner
            rounded
            class="bg-warning text-grey-10"
            v-if="bookingForm.boat?.defects"
          >
            <template v-slot:avatar>
              <q-icon name="warning" color="grey-10" />
            </template>
            {{ bookingForm.boat.name }} currently has the following notices:
            <ol>
              <li
                v-for="defect in bookingForm.boat.defects"
                :key="defect.description"
              >
                {{ defect.description }}
              </li>
            </ol>
          </q-banner>
          <q-card-section>
            <q-btn
              color="primary"
              class="full-width"
              icon="keyboard_arrow_down"
              icon-right="keyboard_arrow_down"
              label="Next: Crew & Passengers"
              @click="resourceView = false"
          /></q-card-section>
        </q-expansion-item>
        <q-expansion-item
          expand-separator
          icon="people"
          label="Crew and Passengers"
          default-opened
        >
          <q-separator />
        </q-expansion-item>

        <q-item-section>
          <q-btn label="Submit" type="submit" color="primary" />
        </q-item-section> </q-form
    ></q-list>
  </q-page>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue';
import { useAuthStore } from 'src/stores/auth';
import { Boat, useBoatStore } from 'src/stores/boat';
import { Dialog, date } from 'quasar';
import ResourceScheduleViewerComponent from 'src/components/ResourceScheduleViewerComponent.vue';
import { makeDateTime } from '@quasar/quasar-ui-qcalendar';
import { useScheduleStore, Reservation } from 'src/stores/schedule';

const auth = useAuthStore();
const dateFormat = 'ddd MMM D, YYYY h:mm A';
const resourceView = ref(true);
const scheduleStore = useScheduleStore();
const bookingForm = reactive({
  bookingId: scheduleStore.getNewId(),
  name: auth.currentUser?.name,
  boat: <Boat | undefined>undefined,
  startDate: date.formatDate(new Date(), dateFormat),
  endDate: computed(() =>
    date.formatDate(
      date.addToDate(bookingForm.startDate, {
        hours: bookingForm.duration,
      }),
      dateFormat
    )
  ),
  duration: 1,
});

watch(bookingForm, (b, a) => {
  const newRes = <Reservation>{
    id: b.bookingId,
    user: b.name,
    resource: b.boat,
    start: date.extractDate(b.startDate, dateFormat),
    end: date.extractDate(b.endDate, dateFormat),
    reservationDate: new Date(),
    status: 'tentative',
  };
  //TODO: Turn this into a validator.
  scheduleStore.isOverlapped(newRes)
    ? Dialog.create({ message: 'This booking overlaps another!' })
    : scheduleStore.addOrCreateReservation(newRes);
});

const onReset = () => {
  // TODO
};

const onSubmit = () => {
  // TODO
};

const onClickTime = (data) => {
  bookingForm.boat = data.scope.resource;
  bookingForm.startDate = date.formatDate(
    date.addToDate(makeDateTime(data.scope.timestamp), { hours: 5 }), // A terrible hack to convert back to EST.  TODO: FIX!!!!
    dateFormat
  );
  console.log(bookingForm.startDate);
};
const bookingDuration = computed(() => {
  const diff = date.getDateDiff(
    bookingForm.endDate,
    bookingForm.startDate,
    'minutes'
  );
  return diff <= 0
    ? 'Invalid'
    : (diff > 60 ? Math.trunc(diff / 60) + ' hours' : '') +
        (diff % 60 > 0 ? ' ' + (diff % 60) + ' minutes' : '');
});

const bookingSummary = computed(() => {
  return bookingForm.boat && bookingForm.startDate && bookingForm.endDate
    ? `${bookingForm.boat.name} @ ${bookingForm.startDate} for ${bookingDuration.value}`
    : '';
});

const limitDate = (startDate: string) => {
  return date.isBetweenDates(
    startDate,
    new Date(),
    date.addToDate(new Date(), { days: 21 }),
    { inclusiveFrom: true, inclusiveTo: true, onlyDate: true }
  );
};
</script>
