<script setup>
import { useRoute } from 'vue-router';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { useState } from 'composables/useState';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInput from 'components/common/VnInput.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

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

const isNew = Boolean(!route.params.id);
const clientList = ref([]);
const agencyList = ref([]);
const addressList = ref([]);

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).addressFk = 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 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) => {
    try {
        const { data } = await axios.get(`Clients/${clientId}`);
        await fetchAddressList(data.defaultAddressFk);
    } catch (error) {
        console.error('Error al cambiar el cliente:', error);
    }
};
</script>

<template>
    <VnSubToolbar v-if="isNew" />
    <div class="q-pa-md">
        <FormModel
            :url="`Orders/${route.params.id}`"
            :url-update="`Orders/${route.params.id}/updateBasicData`"
            :model="ORDER_MODEL"
            :filter="orderFilter"
            @on-fetch="fetchOrderDetails"
            auto-load
        >
            <template #form="{ data }">
                <VnRow>
                    <VnSelect
                        url="Clients"
                        :label="t('order.form.clientFk')"
                        v-model="data.clientFk"
                        :options="clientList"
                        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
                        :label="t('order.form.addressFk')"
                        v-model="data.addressFk"
                        :options="addressList"
                        option-value="id"
                        option-label="street"
                        hide-selected
                        :disable="!addressList?.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>
                    <VnInputDate
                        placeholder="dd-mm-aaa"
                        :label="t('order.form.landed')"
                        v-model="data.landed"
                        @update:model-value="
                            () => fetchAgencyList(data.landed, data.addressFk)
                        "
                    />
                    <VnSelect
                        :label="t('order.form.agencyModeFk')"
                        v-model="data.agencyModeFk"
                        :options="agencyList"
                        option-value="agencyModeFk"
                        option-label="agencyMode"
                        hide-selected
                        :disable="!agencyList?.length && data.isConfirmed === 1"
                        clearable
                        emit-value
                        map-options
                        :model-value="
                            !data.isConfirmed &&
                            agencyList?.length &&
                            agencyList.some(
                                (agency) => agency.agencyModeFk === data.agency_id
                            )
                                ? data.agencyModeFk
                                : null
                        "
                    />
                </VnRow>
                <VnRow>
                    <VnInput
                        :label="t('globals.notes')"
                        type="textarea"
                        v-model="data.note"
                        fill-input
                        autogrow
                    />
                </VnRow>
            </template>
        </FormModel>
    </div>
</template>

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