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

import VnSelect from 'src/components/common/VnSelect.vue';
import { useArrayData } from 'src/composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import FetchData from 'src/components/FetchData.vue';

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

const deliveryMethodFk = ref('delivery');
const deliveryMethods = ref({});
const inq = ref([]);
const formData = reactive({});

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

const deliveryMethodsConfig = { pickUp: ['PICKUP'], delivery: ['AGENCY', 'DELIVERY'] };
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 () => {
    formData.geoFk = arrayData.store?.userParams?.geoFk;
    formData.agencyModeFk = arrayData.store?.userParams?.agencyModeFk;
    if (formData.geoFk || formData.agencyModeFk) await fetchData();
});
watch(
    () => deliveryMethodFk.value,
    () => {
        inq.value = {
            deliveryMethodFk: { inq: deliveryMethods.value[deliveryMethodFk.value] },
        };
    }
);
</script>

<template>
    <FetchData
        url="DeliveryMethods"
        :fields="['id', 'name', 'deliveryMethodFk']"
        @on-fetch="
            (data) => {
                Object.entries(deliveryMethodsConfig).forEach(([key, value]) => {
                    deliveryMethods[key] = data
                        .filter((code) => value.includes(code.code))
                        .map((method) => method.id);
                });
                inq = {
                    deliveryMethodFk: { inq: deliveryMethods[deliveryMethodFk] },
                };
            }
        "
        auto-load
    />
    <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', 'countryFk']"
                sort-by="code, townFk"
                option-value="geoFk"
                option-label="code"
                :filter-options="['code', 'geoFk']"
                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?.name }}</QItemLabel
                            >
                        </QItemSection>
                    </QItem>
                </template>
            </VnSelect>
            <VnSelect
                data-key="delivery"
                v-if="deliveryMethodFk == 'delivery'"
                :label="t('deliveryPanel.agency')"
                v-model="formData.agencyModeFk"
                url="AgencyModes/isActive"
                :fields="['id', 'name']"
                :where="inq"
                sort-by="name ASC"
                option-value="id"
                option-label="name"
                hide-selected
                dense
                outlined
                rounded
            />
            <VnSelect
                v-else
                :label="t('deliveryPanel.warehouse')"
                v-model="formData.agencyModeFk"
                url="AgencyModes/isActive"
                :fields="['id', 'name']"
                :where="inq"
                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>
