  <script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {useShowStore} from "@/stores/show.store.ts";
import {showRepetitionData} from "@models/show/ShowRepetition.ts";
import DaysCheckbox from "@partials/fields/show/DaysCheckbox.vue";
import ShowStartEndTime from "@partials/fields/show/ShowStartEndTime.vue";

// Emits and props
const emits = defineEmits(['toggle-show-schedule-form', 'trigger-show-creation'])

// Store
const showStore = useShowStore();

// Data
const checkBoxEnd = ref(false)
const checkBoxRepetition = ref(false)
const isFormValid = ref(false)

// Funcs
onMounted(() => {
  const startDayShow = showStore.currentShow.showDays.firstShow.getDay();
  let showDays = checkBoxRepetition.value ? showStore.currentShow.showDays.day : [];
  showDays.push(startDayShow);
  showStore.updateShowDaysField({ key: 'day', value: showDays });
});

const updateShowStartDay = (newStartDate) => {
  const previousStartDayShow = showStore.currentShow.showDays.firstShow.getDay();
  let showDays = showStore.currentShow.showDays.day.filter((item) => item !== previousStartDayShow);

  showStore.updateShowDaysField({ key: 'firstShow', value: newStartDate });
  const newStartDayShow = newStartDate.getDay();
  showDays.push(newStartDayShow);
  showStore.updateShowDaysField({ key: 'day', value: showDays });
};

const goBack = () => {
  emits("toggle-show-schedule-form");
};

const saveShowSchedule = async () => {
  if (showStore.currentShow.id) {
    return await showStore.updateShowDays();
  }
  emits('trigger-show-creation')
};

watch(checkBoxEnd, (checkBoxEnd) => {
  if(checkBoxEnd == false) showStore.updateShowDaysField({ key: 'lastShow', value: null })
})

watch(checkBoxRepetition, (newValue) => {
  if (!newValue) {
    const startDayShow = showStore.currentShow.showDays.firstShow.getDay();
    showStore.updateShowDaysField({ key: 'day', value: [startDayShow] });
    showStore.updateShowDaysField({ key: 'repeatType', value: 'noRepeat' });
  }
});

// TODO Create a fixed selected day for repetition extracted from the start date
// Create a local ref var that get's the day number from the startDate, pass it
// to the days component as a fixed date
</script>

<template>
  <v-card>
    <v-card-title>
      <h3>Regole di programmazione</h3>
    </v-card-title>
    <v-form ref="form" v-model="isFormValid">
      <v-card-text>
        <v-row no-gutters>
          <!-- First Show Date -->
          <v-col cols="12" md="6" lg="4">
            <v-date-picker
                :value="showStore.currentShow.showDays.firstShow"
                :min="new Date().toISOString().substring(0, 10)"
                :title="'Data inizio'"
                label="Data inizio"
                density="compact"
                required="true"
                v-on:update:modelValue="updateShowStartDay"
            />
          </v-col>

          <!-- Last Show Date with Checkbox Conditional -->
          <v-col cols="12" md="6" lg="4">
            <v-checkbox
                label="impostare una data di fine per lo show?"
                v-model="checkBoxEnd"
            ></v-checkbox>
            <v-date-picker
                :v-model="showStore.currentShow.showDays.lastShow"
                :min="showStore.currentShow.showDays.firstShow"
                label="Data fine"
                title="Data fine"
                density="compact"
                :disabled="!checkBoxEnd"
            />
          </v-col>

          <!-- Start Time and Duration -->
          <v-col cols="12" md="6" lg="4">
            <ShowStartEndTime
                v-model="showStore.currentShow.showDays.startTime"
                :start-time-label="'Ora inizio show'"
                :duration-label="'Durata'"
                :end-time-label="'Orario di fine della trasmissione'"
                @update:duration="value => showStore.updateShowDaysField({ key: 'duration', value })"
                required="true"
            />
          </v-col>

          <!-- Repeat Options -->
          <v-col cols="12" md="6" lg="4">
            <v-checkbox
                label="Attivare regole di ripetizione?"
                v-model="checkBoxRepetition"
            ></v-checkbox>
            <v-select
                v-model="showStore.currentShow.showDays.repeatType"
                :items="showRepetitionData"
                label="Ripetizione"
                density="compact"
                item-title="repeatName"
                item-value="type"
                :disabled="!checkBoxRepetition"
            />

            <DaysCheckbox
                v-model="showStore.currentShow.showDays.day"
                :disabled="!checkBoxRepetition || (showStore.currentShow.showDays.repeatType === 'noRepeat')"
                :fixedDay="showStore.currentShow.showDays.firstShow.getDay()"
                @update:modelValue="value => showStore.updateShowDaysField({ key: 'day', value })"
                label="Giorni"
            />
          </v-col>
        </v-row>
      </v-card-text>

      <v-card-actions>
        <v-btn color="accent" @click="goBack">Torna indietro</v-btn>
        <v-btn color="accent" @click="saveShowSchedule" :disabled="!isFormValid">Salva</v-btn>
      </v-card-actions>
    </v-form>
  </v-card>
</template>