<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 { getClient } from 'src/pages/Customer/composables/getClient';
import { getAddresses } from 'src/pages/Customer/composables/getAddresses';
import { getAgencies } from 'src/pages/Route/Agency/composables/getAgencies';

import { useState } from 'composables/useState';

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);
});

function resetAgenciesSelector(formData) {
    agenciesOptions.value = [];
    formData.agencyModeId = null;
}

const fetchClient = async (formData) => {
    const response = await getClient(formData.clientId);
    if (!response) return;
    const [client] = response.data;
    selectedClient.value = client;
};

const fetchAddresses = async (formData) => {
    const response = await getAddresses(formData.clientId);
    if (!response) return;
    addressesOptions.value = response.data;

    const { defaultAddress } = selectedClient.value;
    formData.addressId = defaultAddress.id;
};

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

const fetchAvailableAgencies = async (formData) => {
    resetAgenciesSelector(formData);
    const response= await getAgencies(formData, selectedClient.value);
    if (!response) return;
    
    const { options, agency } =  response
    if(options)
        agenciesOptions.value = options;
    if(agency)
        formData.agencyModeId = agency;
};

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('globals.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('globals.landed')"
                            v-model="data.landed"
                            @update:model-value="() => fetchAvailableAgencies(data)"
                        />
                    </div>
                </VnRow>
                <VnRow>
                    <div class="col">
                        <VnSelect
                            :label="t('globals.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('globals.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>
