<script setup>
import { useRouter } from 'vue-router';
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { useState } from 'composables/useState';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import { useDialogPluginComponent } from 'quasar';
import { reactive } from 'vue';
import FetchData from 'components/FetchData.vue';

const { t } = useI18n();
const state = useState();
const ORDER_MODEL = 'order';

const router = useRouter();
const agencyList = ref([]);
const addressList = ref([]);
defineEmits(['confirm', ...useDialogPluginComponent.emits]);

const fetchAddressList = async (addressId) => {
    try {
        const { data } = await axios.get('addresses', {
            params: {
                filter: JSON.stringify({
                    fields: ['id', 'nickname', 'street', 'city'],
                    where: { id: addressId },
                }),
            },
        });
        addressList.value = data;
        if (addressList.value?.length === 1) {
            state.get(ORDER_MODEL).addressId = addressList.value[0].id;
        }
    } catch (err) {
        console.error(`Error fetching addresses`, err);
        return err.response;
    }
};

const fetchAgencyList = async (landed, addressFk) => {
    if (!landed || !addressFk) {
        return;
    }
    try {
        const { data } = await axios.get('Agencies/landsThatDay', {
            params: {
                addressFk,
                landed: new Date(landed).toISOString(),
            },
        });
        agencyList.value = data;
    } catch (err) {
        console.error(`Error fetching agencies`, err);
        return err.response;
    }
};

// const fetchOrderDetails = (order) => {
//     fetchAddressList(order?.addressFk);
//     fetchAgencyList(order?.landed, order?.addressFk);
// };
const $props = defineProps({
    clientFk: {
        type: Number,
        default: null,
    },
});
const initialFormState = reactive({
    active: true,
    addressId: null,
    clientFk: $props.clientFk,
});
// const orderMapper = (order) => {
//     return {
//         addressId: order.addressFk,
//         agencyModeId: order.agencyModeFk,
//         landed: new Date(order.landed).toISOString(),
//     };
// };
// const orderFilter = {
//     include: [
//         { relation: 'agencyMode', scope: { fields: ['name'] } },
//         {
//             relation: 'address',
//             scope: { fields: ['nickname'] },
//         },
//         { relation: 'rows', scope: { fields: ['id'] } },
//         {
//             relation: 'client',
//             scope: {
//                 fields: [
//                     'salesPersonFk',
//                     'name',
//                     'isActive',
//                     'isFreezed',
//                     'isTaxDataChecked',
//                 ],
//                 include: {
//                     relation: 'salesPersonUser',
//                     scope: { fields: ['id', 'name'] },
//                 },
//             },
//         },
//     ],
// };

const onClientChange = async (clientId = $props.clientFk) => {
    try {
        const { data } = await axios.get(`Clients/${clientId}`);
        await fetchAddressList(data.defaultAddressFk);
    } catch (error) {
        console.error('Error al cambiar el cliente:', error);
    }
};

async function onDataSaved(_, id) {
    await router.push({ path: `/order/${id}/catalog` });
}
onMounted(async () => {
    await onClientChange();
});
</script>

<template>
    <FormModelPopup
        url-create="Orders/new"
        :title="t('Create Order')"
        @on-data-saved="onDataSaved"
        :model="ORDER_MODEL"
        :filter="orderFilter"
        :form-initial-data="initialFormState"
    >
        <template #form-inputs="{ data }">
            <VnRow class="row q-gutter-md q-mb-md">
                <VnSelect
                    url="Clients"
                    :label="t('order.form.clientFk')"
                    v-model="data.clientFk"
                    option-value="id"
                    option-label="name"
                    :filter="{
                        fields: ['id', 'name', 'defaultAddressFk'],
                    }"
                    hide-selected
                    @update:model-value="onClientChange"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel>
                                    {{ `${scope.opt.id}: ${scope.opt.name}` }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
                <VnSelect
                    ref="addressRef"
                    :label="t('order.form.addressFk')"
                    v-model="data.addressId"
                    url="addresses"
                    :fields="['id', 'nickname', 'defaultAddressFk', 'street', 'city']"
                    sort-by="id"
                    option-value="id"
                    option-label="street"
                    hide-selected
                    :disable="!$refs.addressRef?.length"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel>
                                    {{
                                        `${scope.opt.nickname}: ${scope.opt.street},${scope.opt.city}`
                                    }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnInputDate
                    placeholder="dd-mm-aaa"
                    :label="t('order.form.landed')"
                    v-model="data.landed"
                    @update:model-value="
                        () => fetchAgencyList(data.landed, data.addressId)
                    "
                />
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnSelect
                    :label="t('order.form.agencyModeFk')"
                    v-model="data.agencyModeId"
                    :options="agencyList"
                    option-value="agencyModeFk"
                    option-label="agencyMode"
                    hide-selected
                    :disable="!agencyList?.length"
                >
                </VnSelect>
            </VnRow>
        </template>
    </FormModelPopup>
</template>

<i18n>
    es:
        No default address found for the client: No hay ninguna dirección asociada a este cliente.
</i18n>
