<template>
  <div class="q-px-sm">
    <CalendarHeaderComponent v-model="selectedDate" />
    <div class="boat-schedule-table-component">
      <QCalendarDay
        ref="calendar"
        class="q-pt-xs"
        flat
        animated
        dense
        v-model="selectedDate"
        :column-count="boats.length"
        @change="scrollToEvent()"
      >
        <template #head-day="{ scope }">
          <div style="text-align: center; font-weight: 800">
            {{ boats[scope.columnIndex].displayName }}
          </div>
        </template>

        <template #day-body="{ scope }">
          <div
            v-for="block in scheduleStore.getTimeblocksForDate(scope.timestamp)"
            :key="block.id"
          >
            <div
              class="timeblock"
              :style="
                blockStyles(block, scope.timeStartPos, scope.timeDurationHeight)
              "
              @click="selectBlock($event, scope, block)"
            >
              Available
            </div>
          </div>
        </template>
      </QCalendarDay>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Timestamp, diffTimestamp, today } from '@quasar/quasar-ui-qcalendar';

import CalendarHeaderComponent from './CalendarHeaderComponent.vue';

import { ref } from 'vue';
import { useBoatStore } from 'src/stores/boat';
import { Timeblock, useScheduleStore } from 'src/stores/schedule';

const scheduleStore = useScheduleStore();
const boatStore = useBoatStore();

const selectedDate = ref(today());

const boats = boatStore.boats;

const calendar = ref<QCalendarDay.QCalendarDay | null>(null);

function blockStyles(
  block: Timeblock,
  timeStartPos: (t: string) => string,
  timeDurationHeight: (d: number) => string
) {
  const s = {
    top: '',
    height: '',
  };
  if (timeStartPos && timeDurationHeight) {
    s.top = timeStartPos(block.start.time) + 'px';
    s.height =
      timeDurationHeight(
        diffTimestamp(block.start, block.end, false) / 1000 / 60
      ) + 'px';
  }
  return s;
}

interface DayBodyScope {
  columnIndex: number;
  timeDurationHeight: string;
  timeStartPos: (time: string, clamp: boolean) => string;
  timestamp: Timestamp;
}

function selectBlock(event: MouseEvent, scope: DayBodyScope, block: Timeblock) {
  const target = event.target as HTMLDivElement;
  target.classList.add('selected');
  target.textContent = 'selected';
}

function scrollToEvent() {
  setTimeout(() => calendar.value?.scrollToTime('09:00'), 0); // Should figure out why we need this setTimeout...
}
</script>

<style lang="sass">
.boat-schedule-table-component
  display: flex
  height: 40vh
.timeblock
  display: flex
  position: absolute
  justify-content: center
  align-items: center
  width: 100%
  opacity: 0.25
  margin: 0 1px
  text-overflow: ellipsis
  overflow: hidden
  font-size: 0.8em
  cursor: pointer
  background: $primary
  color: white
  border: 2px solid black
.selected
  opacity: 1 !important
</style>
