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

import VehicleEventsPanel from './VehicleEventsPanel.vue';
import VehicleCalendarGrid from '../VehicleCalendarGrid.vue';
import VehicleEventInclusionForm from './VehicleEventInclusionForm.vue';

import { useStateStore } from 'stores/useStateStore';
import RightMenu from 'src/components/common/RightMenu.vue';

const { t } = useI18n();
const stateStore = useStateStore();

const firstDay = ref();
const lastDay = ref();
const events = ref([]);
const vehicleEventsPanelRef = ref(null);
const showVehicleEventForm = ref(false);
const vehicleEventsFormProps = reactive({
    isNewMode: true,
    date: null,
    event: null,
});

const refreshEvents = async () => {
    await vehicleEventsPanelRef.value.fetchData();
};

const openForm = (data) => {
    const { date = null, isNewMode, event } = data;
    Object.assign(vehicleEventsFormProps, { date, isNewMode, event });

    showVehicleEventForm.value = true;
};

const onVehicleEventFormClose = () => {
    showVehicleEventForm.value = false;
    vehicleEventsFormProps.value = {};
};
</script>

<template>
    <RightMenu>
        <template #right-panel v-if="stateStore.isHeaderMounted()">
            <VehicleEventsPanel
                ref="vehicleEventsPanelRef"
                :first-day="firstDay"
                :last-day="lastDay"
                :events="events"
                @update:events="events = $event"
            />
        </template>
    </RightMenu>
    <QPage class="q-pa-md flex justify-center">
        <VehicleCalendarGrid
            v-model:events="events"
            v-model:firstDay="firstDay"
            v-model:lastDay="lastDay"
            data-key="VehicleEvents"
            @on-date-selected="openForm"
        />
        <QDialog v-model="showVehicleEventForm" @hide="onVehicleEventFormClose()">
            <VehicleEventInclusionForm
                v-bind="vehicleEventsFormProps"
                :first-day="firstDay"
                :last-day="lastDay"
                @close-form="onVehicleEventFormClose()"
                @refresh-events="refreshEvents()"
            />
        </QDialog>
        <QPageSticky :offset="[20, 20]">
            <QBtn
                @click="openForm({ isNewMode: true }, true)"
                color="primary"
                fab
                icon="add"
                v-shortcut="'+'"
            />
            <QTooltip class="text-no-wrap">
                {{ t('eventsInclusionForm.addEvent') }}
            </QTooltip>
        </QPageSticky>
    </QPage>
</template>
