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

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 axios from 'axios';

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: () => [],
    },
});

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

const route = useRoute();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();

const isNew = computed(() => props.isNewMode);
const dated = ref(null);
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 () => {
    try {
        const params = {
            zoneFk: parseInt(route.params.id),
            date: dated.value,
            geoIds: tickedNodes.value,
        };
        await axios.post('Zones/exclusionGeo', params);
        await refetchEvents();
    } catch (err) {
        console.error('Error creating exclusion geo: ', err);
    }
};

const exclusionCreate = async () => {
    try {
        if (isNew.value)
            await axios.post(`Zones/${route.params.id}/exclusions`, [
                { dated: dated.value },
            ]);
        else
            await axios.post(`Zones/${route.params.id}/exclusions`, {
                dated: dated.value,
            });

        await refetchEvents();
    } catch (err) {
        console.error('Error creating exclusion: ', err);
    }
};

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

const deleteEvent = async () => {
    try {
        if (!props.event) return;
        await axios.delete(`Zones/${route.params.id}/exclusions`);
        await refetchEvents();
    } catch (err) {
        console.error('Error deleting event: ', err);
    }
};

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

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

onMounted(() => {
    if (props.event) {
        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"
    >
        <template #form-inputs>
            <VnRow class="row q-gutter-md q-mb-lg">
                <VnInputDate
                    :label="t('eventsInclusionForm.day')"
                    v-model="dated"
                    :model-value="props.date"
                />
            </VnRow>
            <div class="column q-gutter-y-sm q-mb-md">
                <QRadio
                    v-model="excludeType"
                    dense
                    val="all"
                    :label="t('eventsExclusionForm.all')"
                />
                <QRadio
                    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()
                    )
                "
            />
            <QBtn
                :label="isNew ? t('globals.add') : t('globals.save')"
                type="submit"
                color="primary"
            />
        </template>
    </FormPopup>
</template>
