<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';

import { useAppStore } from 'stores/app';
import { storeToRefs } from 'pinia';

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

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 v-if="isHeaderMounted" to="#actions">
            <QBtn
                :label="t('back')"
                icon="close"
                rounded
                no-caps
                @click="goBack()"
            >
                <QTooltip>
                    {{ t('back') }}
                </QTooltip>
            </QBtn>
        </Teleport>
        <VnForm
            ref="vnFormRef"
            :fetch-form-data-sql="fetchAddressDataSql"
            :columns-to-ignore-update="['countryFk']"
            :create-model-default="{
                field: 'clientFk',
                value: 'account.myUser_getId()'
            }"
            :pks="pks"
            :is-edit-mode="isEditMode"
            :title="t(isEditMode ? 'editAddress' : 'addAddress')"
            table="myAddress"
            schema="hedera"
            @on-data-saved="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:model-value="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:
    accept: Accept
    name: Consignee
    address: Address
    city: City
    postalCode: Zip code
    country: Country
    province: Province
    addressChangedSuccessfully: Address changed successfully
    addAddress: Add address
    editAddress: Edit address
es-ES:
    accept: Aceptar
    name: Consignatario
    address: Dirección
    city: Ciudad
    postalCode: Código postal
    country: País
    province: Provincia
    addressChangedSuccessfully: Dirección modificada correctamente
    addAddress: Añadir dirección
    editAddress: Modificar dirección
ca-ES:
    accept: Acceptar
    name: Consignatari
    address: Direcció
    city: Ciutat
    postalCode: Codi postal
    country: País
    province: Província
    addressChangedSuccessfully: Adreça modificada correctament
    addAddress: Afegir adreça
    editAddress: Modificar adreça
fr-FR:
    accept: Accepter
    name: Destinataire
    address: Numéro Rue
    city: Ville
    postalCode: Code postal
    country: Pays
    province: Province
    addressChangedSuccessfully: Adresse modifié avec succès
    addAddress: Ajouter adresse
    editAddress: Modifier adresse
pt-PT:
    accept: Aceitar
    name: Consignatario
    address: Morada
    city: Concelho
    postalCode: Código postal
    country: País
    province: Distrito
    addressChangedSuccessfully: Morada modificada corretamente
    addAddress: Adicionar morada
    editAddress: Modificar morada
</i18n>
