<script setup>
import { ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';

import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue';

import useCardDescription from 'src/composables/useCardDescription';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const { t } = useI18n();
const route = useRoute();
const quasar = useQuasar();
const router = useRouter();
const { notify } = useNotify();

const entityId = computed(() => {
    return $props.id || route.params.id;
});

const data = ref(useCardDescription());
const setData = (entity) => (data.value = useCardDescription(entity.alias, entity.id));

const removeAlias = () => {
    quasar
        .dialog({
            title: t('Alias will be removed'),
            message: t('Are you sure you want to continue?'),
            ok: {
                push: true,
                color: 'primary',
            },
            cancel: true,
        })
        .onOk(async () => {
            try {
                await axios.delete(`MailAliases/${entityId.value}`);
                notify(t('Alias removed'), 'positive');
                router.push({ name: 'AccountAlias' });
            } catch (err) {
                console.error('Error removing alias');
            }
        });
};
</script>

<template>
    <CardDescriptor
        ref="descriptor"
        :url="`MailAliases/${entityId}`"
        module="Alias"
        @on-fetch="setData"
        data-key="aliasData"
        :title="data.title"
        :subtitle="data.subtitle"
    >
        <template #menu>
            <QItem v-ripple clickable @click="removeAlias()">
                <QItemSection>{{ t('Delete') }}</QItemSection>
            </QItem>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('mailAlias.description')" :value="entity.description" />
        </template>
    </CardDescriptor>
</template>

<i18n>
    en:
        accountRate: Claming rate
    es:
        accountRate: Ratio de reclamación
        Delete: Eliminar
        Alias will be removed: El alias será eliminado
        Are you sure you want to continue?: ¿Seguro que quieres continuar?
        Alias removed: Alias eliminado
</i18n>
