<script setup>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import axios from 'axios';
import moment from 'moment';

import { useArrayData } from 'src/composables/useArrayData';
import { useWeekdayStore } from 'src/stores/useWeekdayStore';
import { useVnConfirm } from 'composables/useVnConfirm';

import VnRow from 'components/ui/VnRow.vue';
import FormPopup from 'components/FormPopup.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import VnWeekdayPicker from 'src/components/common/VnWeekdayPicker.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnInput from 'src/components/common/VnInput.vue';
import { toDateFormat } from 'src/filters/date';

const props = defineProps({
    date: {
        type: Date,
        default: null,
    },
    event: {
        type: Object,
        default: null,
    },
    isNewMode: {
        type: Boolean,
        default: true,
    },
    eventType: {
        type: Boolean,
        default: true,
    },
    isMasiveEdit: {
        type: Boolean,
        default: false,
    },
    zoneIds: {
        type: Array,
        default: () => [],
    },
});

const emit = defineEmits(['onSubmit', 'closeForm']);

const route = useRoute();
const { t } = useI18n();
const weekdayStore = useWeekdayStore();
const { openConfirmationModal } = useVnConfirm();
const quasar = useQuasar();
const isNew = computed(() => props.isNewMode);
const eventInclusionFormData = ref({ wdays: [] });
const dated = ref(props.date || Date.vnNew());
const _inclusionType = ref('indefinitely');
const hasDeletedEvent = ref(false);
const inclusionType = computed({
    get: () => _inclusionType.value,
    set: (val) => {
        _inclusionType.value = val;
        eventInclusionFormData.value.type = val;
    },
});

const arrayData = useArrayData('ZoneEvents');

const createEvent = async () => {
    const defaultMonths = await axios.get('ZoneConfigs');
    const nMonths = defaultMonths.data[0].defaultMonths;

    eventInclusionFormData.value.weekDays = weekdayStore.toSet(
        eventInclusionFormData.value.wdays,
        eventInclusionFormData.value.wdays,
    );

    if (inclusionType.value == 'day') eventInclusionFormData.value.weekDays = '';
    else eventInclusionFormData.value.dated = null;

    if (inclusionType.value != 'range') {
        eventInclusionFormData.value.started = null;
        eventInclusionFormData.value.ended = null;
    }

    const zoneIds = props.zoneIds?.length ? props.zoneIds : [route.params.id];
    for (const zoneId of zoneIds) {
        let today = eventInclusionFormData.value.dated
            ? moment(eventInclusionFormData.value.dated)
            : moment(dated.value);
        let lastDay = today.clone().add(nMonths, 'months').endOf('month');

        const { data } = await axios.get(`Zones/getEventsFiltered`, {
            params: {
                zoneFk: zoneId,
                started: today,
                ended: lastDay,
            },
        });
        const existsExclusion = data.exclusions.find(
            (exclusion) =>
                toDateFormat(exclusion.dated) ===
                toDateFormat(eventInclusionFormData.value.dated),
        );
        if (existsExclusion) {
            await axios.delete(
                `Zones/${existsExclusion?.zoneFk}/exclusions/${existsExclusion?.id}`,
            );
            await refetchEvents();
            hasDeletedEvent.value = true;
        }

        delete eventInclusionFormData.value.id;
        if (isNew.value || hasDeletedEvent.value)
            await axios.post(`Zones/${zoneId}/events`, eventInclusionFormData.value);
        else
            await axios.put(
                `Zones/${zoneId}/events/${props.event?.id}`,
                eventInclusionFormData.value,
            );
        hasDeletedEvent.value = false;
    }
    quasar.notify({
        message: t('globals.dataSaved'),
        type: 'positive',
    });
    await refetchEvents();
    emit('onSubmit');
};

const deleteEvent = async () => {
    if (!props.event) return;
    await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`);
    await refetchEvents();
};

const closeForm = () => {
    emit('closeForm');
};

const refetchEvents = async () => {
    await arrayData.refresh({ append: false });
    closeForm();
};

onMounted(() => {
    if (props.event) {
        dated.value = props.event?.dated;
        eventInclusionFormData.value = { ...props.event };
        inclusionType.value = props.event?.type || 'day';
    } else if (props.date) {
        dated.value = props.date;
        eventInclusionFormData.value.dated = props.date;
        inclusionType.value = 'day';
    } else inclusionType.value = 'indefinitely';
});
</script>

<template>
    <FormPopup
        :title="
            isNew ? t('eventsInclusionForm.addEvent') : t('eventsInclusionForm.editEvent')
        "
        @on-submit="createEvent()"
        :default-cancel-button="false"
        :default-submit-button="false"
    >
        <template #form-inputs>
            <div class="column q-gutter-y-sm q-mb-md">
                <QRadio
                    v-model="inclusionType"
                    dense
                    val="day"
                    :label="t('eventsInclusionForm.oneDay')"
                    data-cy="ZoneEventInclusionDayRadio"
                />
                <QRadio
                    v-if="!props.isMasiveEdit"
                    v-model="inclusionType"
                    dense
                    val="indefinitely"
                    :label="t('eventsInclusionForm.indefinitely')"
                    data-cy="ZoneEventInclusionIndefinitelyRadio"
                />
                <QRadio
                    v-if="!props.isMasiveEdit"
                    v-model="inclusionType"
                    dense
                    val="range"
                    :label="t('eventsInclusionForm.rangeOfDates')"
                    class="q-mb-sm"
                    data-cy="ZoneEventInclusionRangeRadio"
                />
            </div>
            <VnRow>
                <div class="col flex justify-center">
                    <VnInputDate
                        v-if="inclusionType === 'day'"
                        :label="t('eventsExclusionForm.day')"
                        v-model="eventInclusionFormData.dated"
                        class="full-width"
                    />
                    <VnWeekdayPicker
                        v-else
                        v-model:wdays="eventInclusionFormData.wdays"
                    />
                </div>
            </VnRow>
            <VnRow v-if="inclusionType === 'range'" class="row q-gutter-md q-mb-md">
                <VnInputDate
                    :label="t('eventsInclusionForm.from')"
                    v-model="eventInclusionFormData.started"
                />
                <VnInputDate
                    :label="t('eventsInclusionForm.to')"
                    v-model="eventInclusionFormData.ended"
                />
            </VnRow>
            <VnRow>
                <VnInputTime
                    v-model="eventInclusionFormData.hour"
                    :label="t('zone.closing')"
                />
                <VnInput
                    v-model="eventInclusionFormData.travelingDays"
                    :label="t('zone.travelingDays')"
                    type="number"
                    min="0"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-model="eventInclusionFormData.price"
                    :label="t('list.price')"
                    type="number"
                    min="0"
                />
                <VnInput
                    v-model="eventInclusionFormData.priceOptimum"
                    :label="t('list.priceOptimum')"
                    type="number"
                    min="0"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-model="eventInclusionFormData.bonus"
                    :label="t('zone.bonus')"
                    type="number"
                    min="0"
                />
                <VnInput
                    v-model="eventInclusionFormData.m3Max"
                    :label="t('zone.m3Max')"
                    type="number"
                    min="0"
                />
            </VnRow>
        </template>
        <template #custom-buttons>
            <QBtn
                :label="t('globals.cancel')"
                color="primary"
                flat
                class="q-mr-sm"
                v-close-popup
            />
            <QBtn
                v-if="!isNew && eventType === 'event'"
                :label="t('globals.delete')"
                color="primary"
                flat
                class="q-mr-sm"
                @click="
                    openConfirmationModal(
                        t('zone.deleteTitle'),
                        t('zone.deleteSubtitle'),
                        () => deleteEvent(),
                    )
                "
            />
            <QBtn
                :label="isNew ? t('globals.save') : t('globals.add')"
                type="submit"
                color="primary"
            />
        </template>
    </FormPopup>
</template>
