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

import { useArrayData } from 'src/composables/useArrayData';
import axios from 'axios';
import { toDateFormat, toTimeFormat } from 'src/filters/date.js';
import { dashOrCurrency } from 'filters/index';
import { dashIfEmpty } from 'src/filters';
import { useWeekdayStore } from 'src/stores/useWeekdayStore';
import { useVnConfirm } from 'composables/useVnConfirm';

const props = defineProps({
    firstDay: {
        type: Date,
        required: true,
        default: null,
    },
    lastDay: {
        type: Date,
        required: true,
        default: null,
    },
    events: {
        type: Array,
        required: true,
        default: () => [],
    },
    formModeName: {
        type: String,
        required: true,
        default: 'include',
    },
});

const emit = defineEmits(['openZoneForm', 'update:formModeName']);

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

const formName = computed({
    get: () => props.formModeName,
    set: (value) => emit('update:formModeName', value),
});

const params = computed(() => ({
    zoneFk: route.params.id,
    started: props.firstDay,
    ended: props.lastDay,
}));
const arrayData = useArrayData('ZoneEvents', {
    params: params,
    url: `Zones/getEventsFiltered`,
});

const fetchData = async () => {
    try {
        if (!params.value.zoneFk || !params.value.started || !params.value.ended) return;

        await arrayData.applyFilter({
            params: params.value,
        });
    } catch (err) {
        console.error('Error fetching events: ', err);
    }
};

watch(
    params,
    async () => {
        await fetchData();
    },
    { immediate: true, deep: true }
);

const formatWdays = (event) => {
    if (!event.weekDays) return;

    let abrWdays = event.weekDays
        .split(',')
        .map((wday) => weekdayStore.getLocalesMap[wday].localeAbr);

    return abrWdays.length < 7 ? abrWdays.join(', ') : t('eventsPanel.everyday');
};

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

const openInclusionForm = (event) => {
    formName.value = 'include';
    emit('openZoneForm', {
        date: event.dated,
        event,
        isNewMode: false,
        eventType: 'event',
    });
};

onMounted(async () => {
    weekdayStore.initStore();
});
</script>

<template>
    <QForm @submit="onSubmit()">
        <div class="column q-pa-md q-gutter-y-sm">
            <span class="color-vn-label text-subtitle1">{{
                t('eventsPanel.editMode')
            }}</span>
            <QRadio
                v-model="formName"
                dense
                val="include"
                :label="t('eventsPanel.include')"
            />
            <QRadio
                v-model="formName"
                dense
                val="exclude"
                :label="t('eventsPanel.exclude')"
                class="q-mb-sm"
            />
        </div>
        <span class="color-vn-label text-subtitle1 q-px-md">{{
            t('eventsPanel.events')
        }}</span>
        <QList>
            <QItem v-for="(event, index) in events" :key="index" class="event-card">
                <QItemSection left @click="openInclusionForm(event)">
                    <div v-if="event.type == 'day'" class="q-mb-xs">
                        {{ toDateFormat(event.dated) }}
                    </div>
                    <div v-if="event.type != 'day'" class="q-mb-xs">
                        <span v-if="event.weekDays">
                            {{ formatWdays(event) }}
                        </span>
                        <span v-if="event.type == 'range'">
                            ({{ toDateFormat(event.started) }} -
                            {{ toDateFormat(event.ended) }})
                        </span>
                    </div>
                    <span class="color-vn-label">
                        {{ t('eventsPanel.closing') }}:
                        <span class="color-vn-text q-ml-xs">
                            {{ dashIfEmpty(toTimeFormat(event.hour)) }}
                        </span>
                    </span>
                    <span class="color-vn-label">
                        {{ t('eventsPanel.travelingDays') }}:
                        <span class="color-vn-text">
                            {{ dashIfEmpty(event.travelingDays) }}
                        </span>
                    </span>
                    <span class="color-vn-label">
                        {{ t('eventsPanel.price') }}:
                        <span class="color-vn-text">
                            {{ dashOrCurrency(event.price)() }}</span
                        >
                    </span>
                    <span class="color-vn-label">
                        {{ t('eventsPanel.bonus') }}:
                        <span class="color-vn-text">
                            {{ dashOrCurrency(event.bonus)() }}</span
                        >
                    </span>
                    <span class="color-vn-label">
                        {{ t('eventsPanel.m3Max') }}:
                        <span class="color-vn-text"> {{ dashIfEmpty(event.m3Max) }}</span>
                    </span>
                </QItemSection>
                <QItemSection side @click="openInclusionForm(event)">
                    <QBtn
                        icon="delete"
                        flat
                        dense
                        size="md"
                        color="primary"
                        @click.stop="
                            openConfirmationModal(
                                t('eventsPanel.deleteTitle'),
                                t('eventsPanel.deleteSubtitle'),
                                () => deleteEvent(event.id)
                            )
                        "
                    >
                        <QTooltip>{{ t('eventsPanel.delete') }}</QTooltip>
                    </QBtn>
                </QItemSection>
            </QItem>
            <span
                v-if="!events.length"
                class="flex justify-center text-h5 color-vn-label"
            >
                {{ t('globals.noResults') }}
            </span>
        </QList>
    </QForm>
</template>

<style scoped lang="scss">
.event-card {
    display: flex;
    border-bottom: $border-thin-light;
    margin: 0;

    &:hover {
        background-color: var(--vn-accent-color);
        cursor: pointer;
    }
}
</style>
