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

import axios from 'axios';

import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';
import VnSelectCreate from 'src/components/common/VnSelectCreate.vue';
import CustomerCreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue';
import CustomsNewCustomsAgent from 'src/pages/Customer/components/CustomerNewCustomsAgent.vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();

const formInitialData = reactive({ isDefaultAddress: false });

const townsFetchDataRef = ref(null);
const postcodeFetchDataRef = ref(null);
const urlCreate = ref('');

const postcodesOptions = ref([]);
const citiesLocationOptions = ref([]);
const provincesLocationOptions = ref([]);
const agencyModes = ref([]);
const incoterms = ref([]);
const customsAgents = ref([]);

onBeforeMount(() => {
    urlCreate.value = `Clients/${route.params.id}/createAddress`;
    getCustomsAgents();
});

const onPostcodeCreated = async ({ code, provinceFk, townFk }, formData) => {
    await postcodeFetchDataRef.value.fetch();
    await townsFetchDataRef.value.fetch();
    formData.postalCode = code;
    formData.provinceFk = provinceFk;
    formData.city = citiesLocationOptions.value.find((town) => town.id === townFk).name;
};

const getCustomsAgents = async () => {
    const { data } = await axios.get('CustomsAgents');
    customsAgents.value = data;
};

const refreshData = () => {
    getCustomsAgents();
};

const toCustomerConsignees = () => {
    router.push({
        name: 'CustomerConsignees',
        params: {
            id: route.params.id,
        },
    });
};
</script>

<template>
    <FetchData
        @on-fetch="(data) => (postcodesOptions = data)"
        auto-load
        ref="postcodeFetchDataRef"
        url="Postcodes/location"
    />
    <FetchData
        @on-fetch="(data) => (citiesLocationOptions = data)"
        auto-load
        ref="townsFetchDataRef"
        url="Towns/location"
    />
    <FetchData
        @on-fetch="(data) => (provincesLocationOptions = data)"
        auto-load
        url="Provinces/location"
    />
    <fetch-data
        @on-fetch="(data) => (agencyModes = data)"
        auto-load
        url="AgencyModes/isActive"
    />
    <fetch-data @on-fetch="(data) => (incoterms = data)" auto-load url="Incoterms" />

    <FormModel
        :form-initial-data="formInitialData"
        :observe-form-changes="false"
        :url-create="urlCreate"
        @on-data-saved="toCustomerConsignees()"
        model="client"
    >
        <template #form="{ data, validate }">
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <QCheckbox :label="t('Default')" v-model="data.isDefaultAddress" />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnInput :label="t('Consignee')" v-model="data.nickname" />
                </div>
                <div class="col">
                    <VnInput :label="t('Street address')" v-model="data.street" />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectCreate
                        :label="t('Postcode')"
                        :options="postcodesOptions"
                        :roles-allowed-to-create="['deliveryAssistant']"
                        :rules="validate('Worker.postcode')"
                        hide-selected
                        option-label="code"
                        option-value="code"
                        v-model="data.postalCode"
                    >
                        <template #form>
                            <CustomerCreateNewPostcode
                                @on-data-saved="onPostcodeCreated($event, data)"
                            />
                        </template>
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection v-if="scope.opt">
                                    <QItemLabel>{{ scope.opt.code }}</QItemLabel>
                                    <QItemLabel caption>
                                        {{ scope.opt.code }} -
                                        {{ scope.opt.town.name }}
                                        ({{ scope.opt.town.province.name }},
                                        {{ scope.opt.town.province.country.country }})
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectCreate>
                </div>
                <div class="col">
                    <!-- ciudades -->
                    <VnSelectFilter
                        :label="t('City')"
                        :options="citiesLocationOptions"
                        hide-selected
                        option-label="name"
                        option-value="name"
                        v-model="data.city"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>{{ scope.opt.name }}</QItemLabel>
                                    <QItemLabel caption>
                                        {{
                                            `${scope.opt.name}, ${scope.opt.province.name} (${scope.opt.province.country.country})`
                                        }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectFilter>
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Province')"
                        :options="provincesLocationOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="data.provinceFk"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>{{
                                        `${scope.opt.name} (${scope.opt.country.country})`
                                    }}</QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelectFilter>
                </div>
                <div class="col">
                    <VnSelectFilter
                        :label="t('Agency')"
                        :options="agencyModes"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="data.agencyModeFk"
                    />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnInput :label="t('Phone')" v-model="data.phone" />
                </div>
                <div class="col">
                    <VnInput :label="t('Mobile')" v-model="data.mobile" />
                </div>
            </VnRow>

            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelectFilter
                        :label="t('Incoterms')"
                        :options="incoterms"
                        hide-selected
                        option-label="name"
                        option-value="code"
                        v-model="data.incotermsFk"
                    />
                </div>
                <div class="col">
                    <VnSelectCreate
                        :label="t('Customs agent')"
                        :options="customsAgents"
                        hide-selected
                        option-label="fiscalName"
                        option-value="id"
                        v-model="data.customsAgentFk"
                    >
                        <template #form>
                            <CustomsNewCustomsAgent @on-data-saved="refreshData()" />
                        </template>
                    </VnSelectCreate>
                </div>
            </VnRow>
        </template>
    </FormModel>
</template>

<style lang="scss" scoped>
.add-icon {
    cursor: pointer;
    background-color: $primary;
    border-radius: 50px;
}
</style>

<i18n>
es:
    Default: Predeterminado
    Consignee: Consignatario
    Street address: Dirección postal
    Postcode: Código postal
    City: Población
    Province: Provincia
    Agency: Agencia
    Phone: Teléfono
    Mobile: Movíl
    Incoterms: Incoterms
    Customs agent: Agente de aduanas
</i18n>
