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

import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnForm from 'src/components/common/VnForm.vue';

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

const vnFormRef = ref(null);
const countriesOptions = ref([]);
const provincesOptions = ref([]);
const pks = { id: route.params.id };
const isEditMode = route.params.id !== '0';
const fetchAddressDataSql = {
    query: `
        SELECT a.id, a.street, a.nickname, a.city, a.postalCode, a.provinceFk, p.countryFk
        FROM myAddress a
        LEFT JOIN vn.province p ON p.id = a.provinceFk
        WHERE a.id = #address
    `,
    params: { address: route.params.id }
};

watch(
    () => vnFormRef?.value?.formData?.countryFk,
    async val => await getProvinces(val)
);

const goBack = () => router.push({ name: 'AddressesList' });

const getCountries = async () => {
    countriesOptions.value = await jApi.query(
        `SELECT id, name FROM vn.country
        ORDER BY name`
    );
};

const getProvinces = async countryFk => {
    if (!countryFk) return;
    provincesOptions.value = await jApi.query(
        `SELECT id, name FROM vn.province
        WHERE countryFk = #id
        ORDER BY name`,
        { id: countryFk }
    );
};

onMounted(() => getCountries());
</script>

<template>
    <QPage class="q-pa-md flex justify-center">
        <Teleport :to="$actions">
            <QBtn
                :label="t('back')"
                icon="close"
                rounded
                no-caps
                @click="goBack()"
            />
        </Teleport>
        <VnForm
            ref="vnFormRef"
            :fetchFormDataSql="fetchAddressDataSql"
            :columnsToIgnoreUpdate="['countryFk']"
            :createModelDefault="{
                field: 'clientFk',
                value: 'account.myUser_getId()'
            }"
            :pks="pks"
            :isEditMode="isEditMode"
            :title="t('addEditAddress')"
            table="myAddress"
            schema="hedera"
            @onDataSaved="goBack()"
        >
            <template #form="{ data }">
                <VnInput v-model="data.nickname" :label="t('name')" />
                <VnInput v-model="data.street" :label="t('address')" />
                <VnInput v-model="data.city" :label="t('city')" />
                <VnInput v-model="data.postalCode" :label="t('postalCode')" />
                <VnSelect
                    v-model="data.countryFk"
                    :label="t('country')"
                    :options="countriesOptions"
                    @update:modelValue="data.provinceFk = null"
                />
                <VnSelect
                    v-model="data.provinceFk"
                    :label="t('province')"
                    :options="provincesOptions"
                />
            </template>
        </VnForm>
    </QPage>
</template>

<style lang="scss" scoped>
.form-container {
    width: 100%;
    height: max-content;
    max-width: 544px;
    padding: 32px;
}
</style>

<i18n lang="yaml">
en-US:
    back: Back
    accept: Accept
    addEditAddress: Add or edit address
    name: Consignee
    address: Address
    city: City
    postalCode: Zip code
    country: Country
    province: Province
    addressChangedSuccessfully: Address changed successfully
es-ES:
    back: Volver
    accept: Aceptar
    addEditAddress: Añadir o modificar dirección
    name: Consignatario
    address: Morada
    city: Ciudad
    postalCode: Código postal
    country: País
    province: Distrito
    addressChangedSuccessfully: Dirección modificada correctamente
ca-ES:
    back: Tornar
    accept: Acceptar
    addEditAddress: Afegir o modificar adreça
    name: Consignatari
    address: Direcció
    city: Ciutat
    postalCode: Codi postal
    country: País
    province: Província
    addressChangedSuccessfully: Adreça modificada correctament
fr-FR:
    back: Retour
    accept: Accepter
    addEditAddress: Ajouter ou modifier l'adresse
    name: Destinataire
    address: Numéro Rue
    city: Ville
    postalCode: Code postal
    country: Pays
    province: Province
    addressChangedSuccessfully: Adresse modifié avec succès
pt-PT:
    back: Voltar
    accept: Aceitar
    addEditAddress: Adicionar ou modificar morada
    name: Consignatario
    address: Morada
    city: Concelho
    postalCode: Código postal
    country: País
    province: Distrito
    addressChangedSuccessfully: Morada modificada corretamente
</i18n>
