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

import VnPaginate from 'components/ui/VnPaginate.vue';
import AccountMailAliasCreateForm from './AccountMailAliasCreateForm.vue';

import { useVnConfirm } from 'composables/useVnConfirm';
import { useArrayData } from 'composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';

const { t } = useI18n();
const route = useRoute();
const { openConfirmationModal } = useVnConfirm();
const { notify } = useNotify();

const paginateRef = ref(null);
const createMailAliasDialogRef = ref(null);

const arrayData = useArrayData('AccountMailAliases');
const store = arrayData.store;

const loading = ref(false);
const hasAccount = ref(false);
const data = computed(() => {
    const dataCopy = store.data;
    return dataCopy.sort((a, b) => a.alias?.alias.localeCompare(b.alias?.alias));
});

const filter = computed(() => ({
    where: { account: route.params.id },
    include: {
        relation: 'alias',
        scope: {
            fields: ['id', 'alias', 'description'],
        },
    },
}));

const urlPath = 'MailAliasAccounts';

const columns = computed(() => [
    {
        name: 'name',
    },
    {
        name: 'action',
    },
]);

const fetchAccountExistence = async () => {
    try {
        const { data } = await axios.get(`Accounts/${route.params.id}/exists`);
        return data.exists;
    } catch (error) {
        console.error('Error fetching account existence', error);
        return false;
    }
};

const deleteMailAlias = async (row) => {
    try {
        await axios.delete(`${urlPath}/${row.id}`);
        fetchMailAliases();
        notify(t('Unsubscribed from alias!'), 'positive');
    } catch (error) {
        console.error(error);
    }
};

const createMailAlias = async (mailAliasFormData) => {
    try {
        await axios.post(urlPath, mailAliasFormData);
        notify(t('Subscribed to alias!'), 'positive');
        fetchMailAliases();
    } catch (error) {
        console.error(error);
    }
};

const fetchMailAliases = async () => {
    await nextTick();
    paginateRef.value.fetch();
};

const getAccountData = async (reload = true) => {
    loading.value = true;
    hasAccount.value = await fetchAccountExistence();
    if (!hasAccount.value) {
        loading.value = false;
        store.data = [];
        return;
    }
    reload && (await fetchMailAliases());
    loading.value = false;
};

const openCreateMailAliasForm = () => createMailAliasDialogRef.value.show();

watch(
    () => route.params.id,
    () => {
        getAccountData();
    }
);

onMounted(async () => await getAccountData(false));
</script>

<template>
    <QPage class="column items-center q-pa-md">
        <div class="full-width" style="max-width: 400px">
            <QSpinner v-if="loading" color="primary" size="md" />
            <VnPaginate
                ref="paginateRef"
                data-key="AccountMailAliases"
                :filter="filter"
                :url="urlPath"
                auto-load
            >
                <template #body="{ rows }">
                    <QTable
                        v-if="hasAccount && !loading"
                        :rows="data"
                        :columns="columns"
                        hide-header
                    >
                        <template #body="{ row, rowIndex }">
                            <QTr>
                                <QTd>
                                    <div class="column">
                                        <span>{{ row.alias?.alias }}</span>
                                        <span class="color-vn-label">{{
                                            row.alias?.description
                                        }}</span>
                                    </div>
                                </QTd>
                                <QTd style="width: 50px !important">
                                    <QIcon
                                        name="delete"
                                        size="sm"
                                        class="cursor-pointer"
                                        color="primary"
                                        @click.stop.prevent="
                                            openConfirmationModal(
                                                t('User will be removed from alias'),
                                                t('¿Seguro que quieres continuar?'),
                                                () => deleteMailAlias(row, rows, rowIndex)
                                            )
                                        "
                                    >
                                        <QTooltip>
                                            {{ t('globals.delete') }}
                                        </QTooltip>
                                    </QIcon>
                                </QTd>
                            </QTr>
                        </template>
                    </QTable>
                </template>
            </VnPaginate>
            <h5 v-if="!hasAccount" class="text-center">
                {{ t('account.mailForwarding.accountNotEnabled') }}
            </h5>
        </div>
        <QDialog ref="createMailAliasDialogRef">
            <AccountMailAliasCreateForm @on-submit-create-alias="createMailAlias" />
        </QDialog>
        <QPageSticky position="bottom-right" :offset="[18, 18]">
            <QBtn
                fab
                icon="add"
                color="primary"
                @click="openCreateMailAliasForm()"
                shortcut="+"
            >
                <QTooltip>{{ t('warehouses.add') }}</QTooltip>
            </QBtn>
        </QPageSticky>
    </QPage>
</template>

<i18n>
es:
    Unsubscribed from alias!: ¡Desuscrito del alias!
    Subscribed to alias!: ¡Suscrito al alias!
    User will be removed from alias: El usuario será borrado del alias
    Are you sure you want to continue?: ¿Seguro que quieres continuar?
</i18n>
