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

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

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

const provincesOptions = ref([]);
const postcodesOptions = ref([]);
const townsLocationOptions = ref([]);
const viewAction = ref();
const updateAddressId = ref(null);
const newAddressForm = reactive({
    nickname: null,
    street: null,
    postalCode: null,
    city: null,
    provinceFk: null,
    phone: null,
    mobile: null,
});

const onDataSaved = () => {
    router.push({ name: 'SupplierAddresses' });
};

const updateAddressForm = (addressData) => {
    for (let key in newAddressForm) {
        if (key in addressData) {
            newAddressForm[key] = addressData[key];
        }
    }
};

onBeforeMount(() => {
    viewAction.value = route.query.addressData ? 'update' : 'create';

    if (viewAction.value === 'create') newAddressForm.supplierFk = route.params.id;
});

onMounted(() => {
    if (viewAction.value === 'update' && route.query.addressData) {
        const addressData = JSON.parse(route.query.addressData);
        updateAddressId.value = addressData.id;
        updateAddressForm(addressData);
    }
});
</script>

<template>
    <FetchData
        ref="postcodeFetchDataRef"
        url="Postcodes/location"
        @on-fetch="(data) => (postcodesOptions = data)"
        auto-load
    />
    <FetchData
        ref="provincesFetchDataRef"
        @on-fetch="(data) => (provincesOptions = data)"
        auto-load
        url="Provinces"
    />
    <FetchData
        ref="townsFetchDataRef"
        @on-fetch="(data) => (townsLocationOptions = data)"
        auto-load
        url="Towns/location"
    />
    <QPage>
        <FormModel
            model="supplierAddresses"
            :form-initial-data="newAddressForm"
            :url-update="
                viewAction !== 'create' ? `SupplierAddresses/${updateAddressId}` : null
            "
            :url-create="viewAction === 'create' ? 'SupplierAddresses' : null"
            :observe-form-changes="viewAction === 'create'"
            @on-data-saved="onDataSaved()"
        >
            <template #form="{ data, validate }">
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInput
                            v-model="data.nickname"
                            :label="t('supplier.addresses.name')"
                        />
                    </div>
                    <div class="col">
                        <VnInput
                            v-model="data.street"
                            :label="t('supplier.addresses.street')"
                        />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnSelectCreate
                            v-model="data.postalCode"
                            :label="t('supplier.addresses.postcode')"
                            :rules="validate('supplierAddress.postcode')"
                            :roles-allowed-to-create="['deliveryAssistant']"
                            :options="postcodesOptions"
                            option-label="code"
                            option-value="code"
                            hide-selected
                        >
                            <template #form>
                                <CustomerCreateNewPostcode
                                    @on-data-saved="onPostcodeCreated($event)"
                                />
                            </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">
                        <VnSelectFilter
                            :label="t('supplier.addresses.city')"
                            :options="townsLocationOptions"
                            v-model="data.city"
                            hide-selected
                            option-label="name"
                            option-value="id"
                        />
                    </div>
                    <div class="col">
                        <VnSelectFilter
                            :label="t('supplier.addresses.province')"
                            :options="provincesOptions"
                            hide-selected
                            map-options
                            option-label="name"
                            option-value="id"
                            v-model="data.provinceFk"
                        />
                    </div>
                </VnRow>
                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInput
                            v-model="data.phone"
                            :label="t('supplier.addresses.phone')"
                        />
                    </div>
                    <div class="col">
                        <VnInput
                            v-model="data.mobile"
                            :label="t('supplier.addresses.mobile')"
                        />
                    </div>
                </VnRow>
            </template>
        </FormModel>
    </QPage>
</template>
