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

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

const props = defineProps({
    firstDay: {
        type: Date,
        default: null,
    },
    lastDay: {
        type: Date,
        default: null,
    },
    events: {
        type: Array,
        default: () => [],
    },
});

const emit = defineEmits(['openVehicleForm']);
const { t } = useI18n();
const route = useRoute();
const { notify } = useNotify();
const weekdayStore = useWeekdayStore();
const { openConfirmationModal } = useVnConfirm();
const vehicleStates = ref({});
const fetchVehicleState = async () => {
    const vehicles = await axios.get('VehicleStates');
    vehicleStates.value = vehicles.data;
};

const getVehicleStateName = (id) => {
    return vehicleStates.value[id - 1] ?? dashIfEmpty(id - 1);
};

const params = computed(() => ({
    vehicleFk: route.params.id,
    started: props.firstDay,
    finished: props.lastDay,
}));

const arrayData = useArrayData('VehicleEvents', {
    params: params,
    url: `VehicleEvents`,
});

const fetchData = async () => {
    if (!params.value.vehicleFk || !props.firstDay || !props.lastDay) return;

    try {
        await arrayData.applyFilter({
            params: {
                filter: {
                    where: {
                        vehicleFk: route.params.id,
                        and: [
                            {
                                or: [
                                    { started: { lte: props.lastDay } },
                                    { started: null },
                                ],
                            },
                            {
                                or: [
                                    { finished: { gte: props.firstDay } },
                                    { finished: null },
                                ],
                            },
                        ],
                    },
                },
            },
        });
        emit('update:events', arrayData.store.data || []);
    } catch (error) {
        console.error('Error fetching events:', error);
    }
};

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

watch(
    () => props.events,
    (newEvents) => {
        emit('update:events', newEvents);
    },
    { deep: true },
);

const deleteEvent = async (id) => {
    if (!id) return;
    await axios.delete(`VehicleEvents/${id}`);
    notify(t('globals.dataSaved'), 'positive');
    await fetchData();
};

const openInclusionForm = (event) => {
    emit('openVehicleForm', {
        date: event.dated,
        event,
        isNewMode: false,
    });
};

onMounted(async () => {
    weekdayStore.initStore();
    await fetchVehicleState();
});

defineExpose({
    fetchData,
});
</script>

<template>
    <QForm @submit="onSubmit()">
        <div class="column q-pa-md q-gutter-y-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 class="q-mb-xs">
                        <span
                            >({{ toDateFormat(event.started) }} -
                            {{ toDateFormat(event.finished) }})</span
                        >
                    </div>
                    <span class="color-vn-label"
                        >{{ t('globals.description') }}:
                        <span class="color-vn-text q-ml-xs">{{
                            dashIfEmpty(event.description)
                        }}</span>
                    </span>
                    <span class="color-vn-label"
                        >{{ t('globals.state') }}:
                        <span class="color-vn-text">{{
                            getVehicleStateName(event.vehicleStateFk).state
                        }}</span>
                    </span>
                </QItemSection>
                <QItemSection side @click="openInclusionForm(event)">
                    <QBtn
                        icon="delete"
                        data-cy="delete_event"
                        flat
                        dense
                        size="md"
                        color="primary"
                        @click.stop="
                            openConfirmationModal(
                                t('vehicle.deleteTitle'),
                                t('vehicle.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>
