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

import FetchData from 'components/FetchData.vue';
import VnSelect from 'src/components/common/VnSelect.vue';

import { useArrayData } from 'src/composables/useArrayData';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import { watch } from 'vue';

const { t } = useI18n();
const { notify } = useNotify();

const deliveryMethodFk = ref(null);
const deliveryMethods = ref([]);
const formData = reactive({});

const arrayData = useArrayData('ZoneDeliveryDays', {
    url: 'Zones/getEvents',
});

const fetchDeliveryMethods = async (filter) => {
    try {
        const params = { filter: JSON.stringify(filter) };
        const { data } = await axios.get('DeliveryMethods', { params });
        return data.map((deliveryMethod) => deliveryMethod.id);
    } catch (err) {
        console.error('Error fetching delivery methods: ', err);
    }
};

watch(
    () => deliveryMethodFk.value,
    async (val) => {
        let filter;
        if (val === 'pickUp') filter = { where: { code: 'PICKUP' } };
        else filter = { where: { code: { inq: ['DELIVERY', 'AGENCY'] } } };

        deliveryMethods.value = await fetchDeliveryMethods(filter);
    },
    { immediate: true }
);

const fetchData = async (params) => {
    try {
        const { data } = params
            ? await arrayData.applyFilter({
                  params,
              })
            : await arrayData.fetch({ append: false });
        if (!data.events || !data.events.length)
            notify(t('deliveryPanel.noEventsWarning'), 'warning');
    } catch (err) {
        console.error('Error fetching events: ', err);
    }
};

const onSubmit = async () => {
    const params = { deliveryMethodFk: deliveryMethodFk.value, ...formData };
    await fetchData(params);
};

onMounted(async () => {
    deliveryMethodFk.value = 'delivery';
    formData.geoFk = arrayData.store?.userParams?.geoFk;
    formData.agencyModeFk = arrayData.store?.userParams?.agencyModeFk;
    if (formData.geoFk || formData.agencyModeFk) await fetchData();
});
</script>

<template>
    <QForm @submit="onSubmit()" class="q-pa-md">
        <div class="column q-gutter-y-sm">
            <QRadio
                v-model="deliveryMethodFk"
                dense
                val="pickUp"
                :label="t('deliveryPanel.pickup')"
            />
            <QRadio
                v-model="deliveryMethodFk"
                dense
                val="delivery"
                :label="t('deliveryPanel.delivery')"
                class="q-mb-sm"
            />
            <VnSelect
                v-if="deliveryMethodFk === 'delivery'"
                :label="t('deliveryPanel.postcode')"
                v-model="formData.geoFk"
                url="Postcodes/location"
                :fields="['geoFk', 'code', 'townFk']"
                sort-by="code, townFk"
                option-value="geoFk"
                option-label="code"
                option-filter="code"
                hide-selected
                dense
                outlined
                rounded
            >
                <template #option="{ itemProps, opt }">
                    <QItem v-bind="itemProps">
                        <QItemSection v-if="opt.code">
                            <QItemLabel>{{ opt.code }}</QItemLabel>
                            <QItemLabel caption
                                >{{ opt.town?.province?.name }},
                                {{ opt.town?.province?.country?.country }}</QItemLabel
                            >
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                :label="
                    t(
                        deliveryMethodFk === 'delivery'
                            ? 'deliveryPanel.agency'
                            : 'deliveryPanel.warehouse'
                    )
                "
                v-model="formData.agencyModeFk"
                url="AgencyModes/isActive"
                :fields="['id', 'name']"
                :where="{
                    deliveryMethodFk: { inq: deliveryMethods },
                }"
                sort-by="name ASC"
                option-value="id"
                option-label="name"
                hide-selected
                dense
                outlined
                rounded
            />
        </div>
        <QBtn
            :label="t('deliveryPanel.query')"
            type="submit"
            color="primary"
            class="q-mt-md full-width"
            unelevated
            rounded
            dense
        />
    </QForm>
</template>
