<template>
  <q-banner :class="$q.dark.isActive ? 'bg-grey-9' : 'bg-grey-3'">
    Use the calendar to pick a date. Select an available boat and timeslot
    below.
  </q-banner>
  <BoatScheduleTableComponent />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import {
  today,
  parseTimestamp,
  addToDate,
  Timestamp,
} from '@quasar/quasar-ui-qcalendar';
import { Boat, useBoatStore } from 'src/stores/boat';
import { useScheduleStore, Timeblock } from 'src/stores/schedule';
import { computed } from 'vue';
import { date } from 'quasar';
import BoatScheduleTableComponent from './boat/BoatScheduleTableComponent.vue';

interface EventData {
  event: object;
  scope: {
    timestamp: object;
    columnindex: number;
    activeDate: boolean;
    droppable: boolean;
  };
}

const calendar = ref();
const scheduleStore = useScheduleStore();
const selectedDate = ref(today());
const selectedBoatTime = ref();

const disabledBefore = computed(() => {
  const todayTs = parseTimestamp(today()) as Timestamp;
  return addToDate(todayTs, { day: -1 }).date;
});

function monthFormatter() {
  try {
    return new Intl.DateTimeFormat('en-CA' || undefined, {
      month: 'long',
      timeZone: 'UTC',
    });
  } catch (e) {
    //
  }
}

const disabledDays = () => {
  // Placeholder.  This should actually compute days when boats aren't available.
  const days = [];
  const todayTs = parseTimestamp(today()) as Timestamp;
  days.push(addToDate(todayTs, { day: 2 }).date);
  return days;
};

const boatoptions = (boat: Boat) => {
  const options = useScheduleStore()
    .getTimeblocksForDate(date.extractDate(selectedDate.value, 'YYYY-MM-DD'))
    .map((x: Timeblock) => {
      const conflicts = getConflicts(x, boat);
      return {
        label: x.start.time + ' to ' + x.end.time,
        value: boat.id + ':' + x.start.time,
        disable: conflicts.length > 0,
        user: conflicts[0]?.user,
        boat: boat,
        timeblock: x,
      };
    });
  return options;
};

const emit = defineEmits(['onClickTime', 'onUpdateDuration']);

function onPrev() {
  calendar.value.prev();
}
function onNext() {
  calendar.value.next();
}

function onClickDate(data: EventData) {
  return data;
}
function onChange(data: EventData) {
  return data;
}

const getConflicts = (timeblock: Timeblock, boat: Boat) => {
  const start = date.buildDate({
    hour: timeblock.start.hour,
    minute: timeblock.start.minute,
    second: 0,
    millisecond: 0,
  });
  const end = date.buildDate({
    hour: timeblock.end.hour,
    minute: timeblock.end.minute,
    second: 0,
    millisecond: 0,
  });
  return scheduleStore.getConflictingReservations(boat, start, end);
};
</script>
