<template>
  <q-page>
    <div class="col">
      <navigation-bar
        @today="onToday"
        @prev="onPrev"
        @next="onNext" />
    </div>
    <div class="col q-ma-sm">
      <q-calendar-scheduler
        ref="calendar"
        v-model="selectedDate"
        v-model:model-resources="boatStore.boats"
        resource-key="$id"
        resource-label="displayName"
        :weekdays="[1, 2, 3, 4, 5, 6, 0]"
        :view="$q.screen.gt.md ? 'week' : 'day'"
        v-touch-swipe.mouse.left.right="handleSwipe"
        :max-days="$q.screen.lt.sm ? 3 : 7"
        animated
        bordered
        style="--calendar-resources-width: 40px">
        <template #day="{ scope }">
          <div
            v-for="interval in getSortedIntervals(
              scope.timestamp,
              scope.resource
            )"
            :key="interval.$id"
            class="q-pb-xs row"
            @click="createReservationFromInterval(interval)">
            <q-badge
              multi-line
              :class="!interval.user ? 'cursor-pointer' : null"
              class="col-12 q-pa-sm"
              :transparent="interval.user != undefined"
              :color="interval.user ? 'secondary' : 'primary'"
              :outline="!interval.user"
              :id="interval.id">
              {{
                interval.user
                  ? useAuthStore().getUserNameById(interval.user)
                  : 'Available'
              }}
              <br />
              {{ formatTime(interval.start) }} to
              <br />
              {{ formatTime(interval.end) }}
            </q-badge>
          </div>
        </template>
      </q-calendar-scheduler>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { useReservationStore } from 'src/stores/reservation';
import { ref } from 'vue';
import { useAuthStore } from 'src/stores/auth';

const reservationStore = useReservationStore();
import { getDate } from '@quasar/quasar-ui-qcalendar';
import { QCalendarScheduler } from '@quasar/quasar-ui-qcalendar';
import { Timestamp } from '@quasar/quasar-ui-qcalendar';
import { Boat, useBoatStore } from 'src/stores/boat';
import NavigationBar from 'src/components/scheduling/NavigationBar.vue';
import { useQuasar } from 'quasar';
import { formatTime } from 'src/utils/schedule';
import { useIntervalStore } from 'src/stores/interval';
import { Interval, Reservation } from 'src/stores/schedule.types';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';

const boatStore = useBoatStore();
const calendar = ref();
const $q = useQuasar();
const $router = useRouter();
const { getAvailableIntervals } = useIntervalStore();
const { selectedDate } = storeToRefs(useIntervalStore());
const currentUser = useAuthStore().currentUser;

// interface DayScope {
//   timestamp: Timestamp;
//   columnIndex: number;
//   resource: object;
//   resourceIndex: number;
//   indentLevel: number;
//   activeDate: boolean;
//   droppable: boolean;
// }

const getSortedIntervals = (timestamp: Timestamp, boat?: Boat): Interval[] => {
  return getAvailableIntervals(timestamp, boat)
    .concat(boatReservationEvents(timestamp, boat))
    .sort((a, b) => Date.parse(a.start) - Date.parse(b.start));
};
// Method declarations

// function slotStyle(
//   event: Reservation,
//   timeStartPos: (time: TimestampOrNull) => string,
//   timeDurationHeight: (minutes: number) => string
// ) {
//   const s = {
//     top: '',
//     height: '',
//     'align-items': 'flex-start',
//   };
//   if (timeStartPos && timeDurationHeight) {
//     s.top = timeStartPos(parsed(event.start)) + 'px';
//     s.height =
//       timeDurationHeight(date.getDateDiff(event.end, event.start, 'minutes')) +
//       'px';
//   }
//   return s;
// }

const createReservationFromInterval = (interval: Interval | Reservation) => {
  if (interval.user) {
    if (interval.user === currentUser?.$id) {
      $router.push({ name: 'edit-reservation', params: { id: interval.$id } });
    } else {
      return false;
    }
  } else {
    $router.push({
      name: 'reserve-boat',
      query: { interval: interval.$id },
    });
  }
};

function handleSwipe({ ...event }) {
  event.direction === 'right' ? calendar.value?.prev() : calendar.value?.next();
}
function boatReservationEvents(
  timestamp: Timestamp,
  resource: Boat | undefined
) {
  if (!resource) return [];
  return reservationStore.getReservationsByDate(
    getDate(timestamp),
    (resource as Boat).$id
  );
}
function onToday() {
  calendar.value.moveToToday();
}
function onPrev() {
  calendar.value.prev();
}
function onNext() {
  calendar.value.next();
}
</script>

<style lang="sass">
.q-calendar-scheduler__resource
  background-color: $primary
  color: white
  font-weight: bold
</style>
