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

import CardList from 'src/components/ui/CardList.vue';
import VnList from 'src/components/ui/VnList.vue';
import FetchData from 'src/components/common/FetchData.vue';

import useNotify from 'src/composables/useNotify.js';
import { useVnConfirm } from 'src/composables/useVnConfirm.js';
import { useAppStore } from 'stores/app';
import { storeToRefs } from 'pinia';
import { useUserStore } from 'stores/user';

const router = useRouter();
const jApi = inject('jApi');
const api = inject('api');
const { notify } = useNotify();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();
const appStore = useAppStore();
const userStore = useUserStore();
const { isHeaderMounted } = storeToRefs(appStore);
const fetchAddressesRef = ref(null);

const addresses = ref([]);
const defaultAddress = ref(null);
const clientId = ref(null);

const goToAddressDetails = (id = 0) =>
    router.push({ name: 'addressDetails', params: { id } });

const getDefaultAddress = async () => {
    try {
        const [address] = await jApi.query(
            'SELECT id, defaultAddressFk FROM myClient c'
        );
        defaultAddress.value = address.defaultAddressFk;
        clientId.value = address.id;
    } catch (error) {
        console.error('Error getting default address:', error);
    }
};

const changeDefaultAddress = async () => {
    if (!clientId.value) return;
    await jApi.execQuery(
        `UPDATE myClient
        SET defaultAddressFk = #defaultAddress
        WHERE id = #id;`,
        {
            defaultAddress: defaultAddress.value,
            id: clientId.value
        }
    );
    notify(t('defaultAddressModified'), 'positive');
};

async function removeAddress(address) {
    try {
        await api.patch(
            `/Clients/${userStore?.user?.id}/updateAddress/${address.id}`,
            {
                ...address,
                isActive: false
            }
        );
        fetchAddressesRef.value.fetch();
        notify(t('dataSaved'), 'positive');
    } catch (error) {
        console.error('Error removing address:', error);
    }
}

onMounted(async () => {
    getDefaultAddress();
});
</script>

<template>
    <FetchData
        v-if="userStore?.user?.id"
        ref="fetchAddressesRef"
        url="Addresses"
        :filter="{
            where: { clientFk: userStore.user.id, isActive: true },
            fields: [
                'id',
                'nickname',
                'postalCode',
                'city',
                'street',
                'isActive'
            ]
        }"
        auto-load
        @on-fetch="data => (addresses = data)"
    />
    <Teleport v-if="isHeaderMounted" to="#actions">
        <QBtn
            :label="t('addAddress')"
            icon="add"
            @click="goToAddressDetails()"
            rounded
            no-caps
            data-cy="newAddressBtn"
        >
            <QTooltip>
                {{ t('addAddress') }}
            </QTooltip>
        </QBtn>
    </Teleport>
    <QPage class="vn-w-sm">
        <VnList
            class="rounded-borders shadow-1 shadow-transition"
            separator
            :rows="addresses"
            data-cy="addressCardList"
        >
            <CardList
                v-for="(address, index) in addresses"
                :key="index"
                :rounded="false"
                tag="label"
            >
                <template #prepend>
                    <QRadio
                        v-model="defaultAddress"
                        :val="address.id"
                        class="q-mr-sm"
                        @update:model-value="changeDefaultAddress"
                    />
                </template>
                <template #content>
                    <span class="text-bold q-mb-sm">
                        {{ address.nickname }}
                    </span>
                    <span>{{ address.street }}</span>
                    <span>
                        {{ address.postalCode }},
                        {{ address.city }}
                    </span>
                </template>
                <template #actions>
                    <QBtn
                        icon="delete"
                        flat
                        rounded
                        @click.stop="
                            openConfirmationModal(
                                null,
                                t('confirmDeleteAddress'),
                                () => removeAddress(address)
                            )
                        "
                    >
                        <QTooltip>
                            {{ t('deleteAddress') }}
                        </QTooltip>
                    </QBtn>
                    <QBtn
                        icon="edit"
                        flat
                        rounded
                        @click.stop="goToAddressDetails(address.id)"
                        data-cy="editAddressBtn"
                    >
                        <QTooltip>
                            {{ t('editAddress') }}
                        </QTooltip>
                    </QBtn>
                </template>
            </CardList>
        </VnList>
    </QPage>
</template>

<i18n lang="yaml">
en-US:
    addAddress: Add address
    defaultAddressModified: Default address modified
    confirmDeleteAddress: Are you sure you want to delete the address?
    editAddress: Edit address
    deleteAddress: Delete address
es-ES:
    addAddress: Añadir dirección
    defaultAddressModified: Dirección por defecto modificada
    confirmDeleteAddress: ¿Estás seguro de que quieres borrar la dirección?
    editAddress: Modificar dirección
    deleteAddress: Borrar dirección
ca-ES:
    addAddress: Afegir adreça
    defaultAddressModified: Adreça per defecte modificada
    confirmDeleteAddress: Estàs segur que vols esborrar l'adreça?
    editAddress: Modificar adreça
    deleteAddress: Esborrar adreça
fr-FR:
    addAddress: Ajouter une adresse
    defaultAddressModified: Adresse par défaut modifiée
    confirmDeleteAddress: Êtes-vous sûr de vouloir supprimer l'adresse?
    editAddress: Modifier adresse
    deleteAddress: Supprimer adresse
pt-PT:
    addAddress: Adicionar Morada
    defaultAddressModified: Endereço padrão modificado
    confirmDeleteAddress: Tem a certeza de que deseja excluir o endereço?
    editAddress: Modificar morada
    deleteAddress: Eliminar morada
</i18n>
