<script setup>
import { useRoute, useRouter } from 'vue-router';
import { onBeforeMount, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';

import FormModel from 'components/FormModel.vue';
import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

import { useState } from 'composables/useState';
import axios from 'axios';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const state = useState();
const user = state.getUser();

const initialFormState = reactive({
    clientId: Number(route.query?.clientFk) || null,
    addressId: null,
    agencyModeId: null,
    warehouseId: user.value.warehouseFk,
    landed: null,
});
const clientOptions = ref([]);
const agenciesOptions = ref([]);
const addressesOptions = ref([]);
const warehousesOptions = ref([]);
const selectedClient = ref(null);

onBeforeMount(async () => {
    await onClientSelected(initialFormState);
});

const fetchClient = async (formData) => {
    try {
        const filter = {
            include: {
                relation: 'defaultAddress',
                scope: {
                    fields: ['id', 'agencyModeFk'],
                },
            },
            where: { id: formData.clientId },
        };
        const params = { filter: JSON.stringify(filter) };
        const { data } = await axios.get('Clients', { params });
        const [client] = data;
        selectedClient.value = client;
    } catch (err) {
        console.error('Error fetching client');
    }
};

const fetchAddresses = async (formData) => {
    try {
        if (!formData.clientId) return;

        const filter = {
            fields: ['nickname', 'street', 'city', 'id'],
            where: { isActive: true },
            order: 'nickname ASC',
        };
        const params = { filter: JSON.stringify(filter) };
        const { data } = await axios.get(`Clients/${formData.clientId}/addresses`, {
            params,
        });
        addressesOptions.value = data;

        const { defaultAddress } = selectedClient.value;
        formData.addressId = defaultAddress.id;
    } catch (err) {
        console.error(`Error fetching addresses`, err);
        return err.response;
    }
};

const onClientSelected = async (formData) => {
    await fetchClient(formData);
    await fetchAddresses(formData);
};

const fetchAvailableAgencies = async (formData) => {
    if (!formData.warehouseId || !formData.addressId || !formData.landed) return;
    let params = {
        warehouseFk: formData.warehouseId,
        addressFk: formData.addressId,
        landed: formData.landed,
    };

    const { data } = await axios.get('Agencies/getAgenciesWithWarehouse', { params });

    agenciesOptions.value = data;

    const defaultAgency = agenciesOptions.value.find(
        (agency) =>
            agency.agencyModeFk === selectedClient.value.defaultAddress.agencyModeFk
    );

    if (defaultAgency) formData.agencyModeId = defaultAgency.agencyModeFk;
};

const redirectToTicketList = (_, { id }) => {
    router.push({ name: 'TicketSummary', params: { id } });
};
</script>

<template>
    <FetchData
        url="Clients"
        @on-fetch="(data) => (clientOptions = data)"
        :filter="{ fields: ['id', 'name', 'defaultAddressFk'], order: 'id' }"
        auto-load
    />
    <FetchData
        url="Warehouses"
        @on-fetch="(data) => (warehousesOptions = data)"
        order="name"
        auto-load
    />
    <VnSubToolbar />
    <div class="q-pa-md">
        <FormModel
            url-create="Tickets/new"
            model="ticket"
            :form-initial-data="initialFormState"
            @on-data-saved="redirectToTicketList"
        >
            <template #form="{ data }">
                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('ticket.create.client')"
                            v-model="data.clientId"
                            :options="clientOptions"
                            option-value="id"
                            option-label="name"
                            hide-selected
                            @update:model-value="(client) => onClientSelected(data)"
                        >
                            <template #option="scope">
                                <QItem v-bind="scope.itemProps">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{ scope.opt.name }}
                                        </QItemLabel>
                                        <QItemLabel caption>
                                            {{ `#${scope.opt.id}` }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>
                            </template>
                        </VnSelect>
                    </div>
                </VnRow>
                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('ticket.create.address')"
                            v-model="data.addressId"
                            :options="addressesOptions"
                            option-value="id"
                            option-label="nickname"
                            hide-selected
                            :disable="!data.clientId"
                            @update:model-value="() => fetchAvailableAgencies(data)"
                        >
                            <template #option="scope">
                                <QItem v-bind="scope.itemProps">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{ scope.opt.nickname }}
                                        </QItemLabel>
                                        <QItemLabel caption>
                                            {{ `${scope.opt.street}, ${scope.opt.city}` }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>
                            </template>
                        </VnSelect>
                    </div>
                </VnRow>
                <VnRow>
                    <div class="col">
                        <VnInputDate
                            placeholder="dd-mm-aaa"
                            :label="t('ticket.create.landed')"
                            v-model="data.landed"
                            @update:model-value="() => fetchAvailableAgencies(data)"
                        />
                    </div>
                </VnRow>
                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('ticket.create.warehouse')"
                            v-model="data.warehouseId"
                            :options="warehousesOptions"
                            option-value="id"
                            option-label="name"
                            hide-selected
                            @update:model-value="() => fetchAvailableAgencies(data)"
                        />
                    </div>
                </VnRow>
                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('ticket.create.agency')"
                            v-model="data.agencyModeId"
                            :options="agenciesOptions"
                            option-value="agencyModeFk"
                            option-label="agencyMode"
                            hide-selected
                            :disable="!data.clientId || !data.landed || !data.warehouseId"
                        />
                    </div>
                </VnRow>
            </template>
        </FormModel>
    </div>
</template>
