<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 VnRow from 'components/ui/VnRow.vue';
import FormPopup from 'components/FormPopup.vue';
import ZoneLocationsTree from './ZoneLocationsTree.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import { useArrayData } from 'src/composables/useArrayData';
import { useVnConfirm } from 'composables/useVnConfirm';
import { toDateFormat } from 'src/filters/date';

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

const emit = defineEmits(['onSubmit', 'closeForm']);
const quasar = useQuasar();
const route = useRoute();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();

const isNew = computed(() => props.isNewMode);
const dated = ref(props.date || Date.vnNew());
const tickedNodes = ref();
const _excludeType = ref('all');
const excludeType = computed({
    get: () => _excludeType.value,
    set: (val) => {
        _excludeType.value = val;
    },
});

const arrayData = useArrayData('ZoneEvents');

const exclusionGeoCreate = async () => {
    if (await zoneHasTickets(route.params.id, dated.value)) return;

    const params = {
        zoneFk: parseInt(route.params.id),
        date: dated.value,
        geoIds: tickedNodes.value,
    };
    await axios.post('Zones/exclusionGeo', params);
    quasar.notify({
        message: t('globals.dataSaved'),
        type: 'positive',
    });
    await refetchEvents();
};

const exclusionCreate = async () => {
    const defaultMonths = await axios.get('ZoneConfigs');
    const nMonths = defaultMonths.data[0].defaultMonths;
    const body = {
        dated: dated.value,
    };
    const zoneIds = props.zoneIds?.length ? props.zoneIds : [route.params.id];
    for (const id of zoneIds) {
        if (await zoneHasTickets(id, dated.value)) return;

        const url = `Zones/${id}/exclusions`;
        let today = moment(dated.value);
        let lastDay = today.clone().add(nMonths, 'months').endOf('month');

        const { data } = await axios.get(`Zones/getEventsFiltered`, {
            params: {
                zoneFk: id,
                started: today,
                ended: lastDay,
            },
        });
        const existsEvent = data.events.find(
            (event) => toDateFormat(event.dated) === toDateFormat(dated.value),
        );
        const existsGeoEvent = data.geoExclusions.find(
            (event) => toDateFormat(event.dated) === toDateFormat(dated.value),
        );
        if (existsEvent) {
            await axios.delete(`Zones/${existsEvent?.zoneFk}/events/${existsEvent?.id}`);
        }
        if (existsGeoEvent) {
            await axios.delete(
                `Zones/${existsGeoEvent?.zoneFk}/exclusions/${existsGeoEvent?.zoneExclusionFk}`,
            );
        }

        if (isNew.value || props.event?.type) await axios.post(`${url}`, [body]);
        else await axios.put(`${url}/${props.event?.id}`, body);
    }
    quasar.notify({
        message: t('globals.dataSaved'),
        type: 'positive',
    });
    await refetchEvents();
};

const zoneHasTickets = async (zoneId, date) => {
    const filter = {
        where: {
            zoneFk: zoneId,
            shipped: date,
        },
    };
    const params = { filter: JSON.stringify(filter) };
    const { data } = await axios.get('Tickets', { params });
    if (data.length > 0) {
        quasar.notify({
            message: t('eventsExclusionForm.cantCloseZone'),
            type: 'negative',
        });
        await refetchEvents();
        return true;
    }
    return false;
};

const onSubmit = async () => {
    if (excludeType.value === 'all') exclusionCreate();
    else exclusionGeoCreate();
};

const deleteEvent = async () => {
    if (!props.event) return;
    if (!props.event.created) {
        const filter = {
            where: {
                dated: dated.value,
            },
        };
        const params = { filter: JSON.stringify(filter) };
        const { data: res } = await axios.get(`Zones/${route.params.id}/exclusions`, {
            params,
        });
        if (res) await axios.delete(`Zones/${route.params.id}/exclusions/${res[0].id}`);
    } else {
        const exclusionId = props.event?.zoneExclusionFk || props.event?.id;
        await axios.delete(`Zones/${route.params.id}/exclusions/${exclusionId}`);
    }
    await refetchEvents();
};

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

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

onMounted(() => {
    if (props.event && props.event.dated) {
        dated.value = props.event?.dated;
        excludeType.value =
            props.eventType === 'geoExclusion' ? 'specificLocations' : 'all';
        tickedNodes.value = props.geoIds || [];
    } else if (props.date) dated.value = props.date;
});
</script>

<template>
    <FormPopup
        :title="
            isNew
                ? t('eventsExclusionForm.addExclusion')
                : t('eventsExclusionForm.editExclusion')
        "
        @on-submit="onSubmit()"
        :default-cancel-button="false"
        :default-submit-button="false"
        :submit-on-enter="false"
    >
        <template #form-inputs>
            <VnRow class="row q-gutter-md q-mb-lg">
                <VnInputDate :label="t('eventsInclusionForm.day')" v-model="dated" />
            </VnRow>
            <div class="column q-gutter-y-sm q-mb-md">
                <QRadio
                    v-model="excludeType"
                    dense
                    val="all"
                    :label="t('eventsExclusionForm.all')"
                />
                <QRadio
                    v-if="!props.isMasiveEdit"
                    v-model="excludeType"
                    dense
                    val="specificLocations"
                    :label="t('eventsExclusionForm.specificLocations')"
                />
            </div>
            <div
                v-if="excludeType === 'specificLocations'"
                style="max-height: 60vh; overflow-y: scroll"
            >
                <ZoneLocationsTree
                    :root-label="t('eventsExclusionForm.rootTreeLabel')"
                    v-model:tickedNodes="tickedNodes"
                    show-search-bar
                    show-default-checkboxes
                >
                    <template #content="{ node }">
                        <span>{{ node.name }}</span>
                    </template>
                </ZoneLocationsTree>
            </div>
        </template>
        <template #custom-buttons>
            <QBtn
                :label="t('globals.cancel')"
                color="primary"
                flat
                class="q-mr-sm"
                v-close-popup
            />
            <QBtn
                v-if="
                    !isNew && (eventType === 'exclusion' || eventType === 'geoExclusion')
                "
                :label="t('globals.delete')"
                color="primary"
                flat
                class="q-mr-sm"
                @click="
                    openConfirmationModal(
                        t('eventsPanel.deleteTitle'),
                        t('eventsPanel.deleteSubtitle'),
                        () => deleteEvent(),
                    )
                "
                data-cy="ZoneEventExclusionDeleteBtn"
            />
            <QBtn
                :label="isNew ? t('globals.add') : t('globals.save')"
                type="submit"
                color="primary"
                @click="onSubmit()"
            />
        </template>
    </FormPopup>
</template>
