<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 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 { useArrayData } from 'src/composables/useArrayData';
import { useWeekdayStore } from 'src/stores/useWeekdayStore';
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: Boolean,
        default: true,
    },
});

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

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

const isNew = computed(() => props.isNewMode);
const eventInclusionFormData = ref({ wdays: [] });

const _inclusionType = ref('indefinitely');
const inclusionType = computed({
    get: () => _inclusionType.value,
    set: (val) => {
        _inclusionType.value = val;
        eventInclusionFormData.value.type = val;
    },
});

const arrayData = useArrayData('ZoneEvents');

const createEvent = async () => {
    try {
        eventInclusionFormData.value.weekDays = weekdayStore.toSet(
            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;
        }

        if (isNew.value)
            await axios.post(
                `Zones/${route.params.id}/events`,
                eventInclusionFormData.value
            );
        else
            await axios.put(
                `Zones/${route.params.id}/events/${props.event?.id}`,
                eventInclusionFormData.value
            );

        await refetchEvents();
        emit('onSubmit');
    } catch (err) {
        console.error('Error creating event', err);
    }
};

const deleteEvent = async () => {
    try {
        if (!props.event) return;
        await axios.delete(`Zones/${route.params.id}/events/${props.event?.id}`);
        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) {
        eventInclusionFormData.value = { ...props.event };
        inclusionType.value = props.event?.type || 'day';
    } else if (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')"
                />
                <QRadio
                    v-model="inclusionType"
                    dense
                    val="indefinitely"
                    :label="t('eventsInclusionForm.indefinitely')"
                />
                <QRadio
                    v-model="inclusionType"
                    dense
                    val="range"
                    :label="t('eventsInclusionForm.rangeOfDates')"
                    class="q-mb-sm"
                />
            </div>
            <VnRow>
                <div class="col flex justify-center">
                    <VnInputDate
                        v-if="inclusionType === 'day'"
                        :label="t('eventsInclusionForm.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('eventsInclusionForm.closing')"
                />
                <VnInput
                    v-model="eventInclusionFormData.travelingDays"
                    :label="t('eventsInclusionForm.travelingDays')"
                    type="number"
                    min="0"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-model="eventInclusionFormData.price"
                    :label="t('eventsInclusionForm.price')"
                    type="number"
                    min="0"
                />
                <VnInput
                    v-model="eventInclusionFormData.bonus"
                    :label="t('eventsInclusionForm.bonus')"
                    type="number"
                    min="0"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-model="eventInclusionFormData.m3Max"
                    :label="t('eventsInclusionForm.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('eventsPanel.deleteTitle'),
                        t('eventsPanel.deleteSubtitle'),
                        () => deleteEvent()
                    )
                "
            />
            <QBtn
                :label="isNew ? t('globals.save') : t('globals.add')"
                type="submit"
                color="primary"
            />
        </template>
    </FormPopup>
</template>
