<script setup lang="ts">
import { useIntervalTemplateStore } from '~/stores/intervalTemplate';
import type { IntervalTemplate } from '~/utils/schedule.types';
import { copyIntervalTemplate, timeTuplesOverlapped } from '~/utils/schedule';
import { ref } from 'vue';

const alert = ref(false);
const overlapped = ref();
const intervalTemplateStore = useIntervalTemplateStore();
const props = defineProps<{ edit?: boolean; modelValue: IntervalTemplate }>();
const edit = ref(props.edit);
const expanded = ref(props.edit);
const template = ref(copyIntervalTemplate(props.modelValue));

const emit = defineEmits<{ (e: 'cancel'): void; (e: 'saved'): void }>();

const revert = () => {
  template.value = copyIntervalTemplate(props.modelValue);
  edit.value = false;
  emit('cancel');
};

const toggleEdit = () => {
  edit.value = !edit.value;
};

const deleteTemplate = (event: Event, tmpl: IntervalTemplate | undefined) => {
  if (tmpl?.$id) intervalTemplateStore.deleteIntervalTemplate(tmpl.$id);
};

function onDragStart(e: DragEvent, tmpl: IntervalTemplate) {
  if (e.dataTransfer) {
    e.dataTransfer.dropEffect = 'copy';
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('ID', tmpl.$id || '');
  }
}

const saveTemplate = (evt: Event, tmpl: IntervalTemplate | undefined) => {
  if (!tmpl) return false;
  overlapped.value = timeTuplesOverlapped(tmpl.timeTuples);
  if (overlapped.value.length > 0) {
    alert.value = true;
  } else {
    edit.value = false;
    if (tmpl.$id && tmpl.$id !== 'unsaved') {
      intervalTemplateStore.updateIntervalTemplate(tmpl, tmpl.$id);
    } else {
      intervalTemplateStore.createIntervalTemplate(tmpl);
      emit('saved');
    }
  }
};
</script>

<template>
  <q-expansion-item expand-icon-toggle draggable="true" @dragstart="onDragStart($event, template)" v-model="expanded">
    <template v-slot:header>
      <q-item-section>
        <q-input label="Template name" :borderless="!edit" dense v-model="template.name" v-if="edit" />
        <q-item-label v-if="!edit" class="cursor-pointer">{{ template.name }}</q-item-label>
      </q-item-section>
    </template>
    <q-card flat>
      <q-card-section horizontal>
        <q-card-section class="q-pt-xs">
          <q-list dense>
            <q-item v-for="(item, index) in template.timeTuples" :key="item[0]">
              <q-input class="q-mx-sm" dense v-model="item[0]" type="time" label="Start" :borderless="!edit" :readonly="!edit" />
              <q-input class="q-mx-sm" dense v-model="item[1]" type="time" label="End" :borderless="!edit" :readonly="!edit">
                <template v-slot:after>
                  <q-btn v-if="edit" round dense flat icon="delete" @click="template.timeTuples.splice(index, 1)" />
                </template>
              </q-input>
            </q-item>
          </q-list>
          <q-btn v-if="edit" dense color="primary" size="sm" label="Add interval" @click="template.timeTuples.push(['00:00', '00:00'])" />
        </q-card-section>
        <q-card-actions vertical>
          <q-btn v-if="!edit" color="primary" icon="edit" label="Edit" @click="toggleEdit" />
          <q-btn v-if="edit" color="primary" icon="save" label="Save" @click="saveTemplate($event, template)" />
          <q-btn v-if="edit" color="secondary" icon="cancel" label="Cancel" @click="revert" />
          <q-btn color="negative" icon="delete" label="Delete" v-if="template.$id !== ''" @click="deleteTemplate($event, template)" />
        </q-card-actions>
      </q-card-section>
    </q-card>
  </q-expansion-item>
  <q-dialog v-model="alert">
    <q-card>
      <q-card-section><div class="text-h6">Overlapped blocks!</div></q-card-section>
      <q-card-section class="q-pt-none">
        <q-chip square icon="schedule" v-for="item in overlapped" :key="item.start">
          {{ item.start }}-{{ item.end }}
        </q-chip>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn flat label="OK" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
