<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useDialogPluginComponent } from 'quasar';

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

const props = defineProps({
    data: {
        type: Object,
        requied: true,
        default: null,
    },
    promise: {
        type: Function,
        required: true,
    },
});

defineEmits(['confirm', ...useDialogPluginComponent.emits]);

const { dialogRef, onDialogOK } = useDialogPluginComponent();
const { t } = useI18n();

const address = ref(props.data.address);
const isLoading = ref(false);

async function confirm() {
    const response = { address: address.value };
    if (props.promise) {
        isLoading.value = true;

        try {
            const dataCopy = JSON.parse(JSON.stringify({ ...props.data }));
            delete dataCopy.address;

            Object.assign(response, dataCopy);
            await props.promise(response);
        } finally {
            isLoading.value = false;
        }
    }

    onDialogOK(response);
}
</script>
<template>
    <QDialog ref="dialogRef">
        <QCard class="q-pa-sm">
            <QCardSection class="row items-center q-pb-none">
                <span class="text-h6 text-grey">{{ t('Send email notification') }}</span>
                <QSpace />
                <QBtn icon="close" flat round dense v-close-popup />
            </QCardSection>
            <QCardSection class="row items-center">
                {{ t('The notification will be sent to the following address') }}
            </QCardSection>
            <QCardSection class="q-pt-none">
                <VnInput
                    v-model="address"
                    is-outlined
                    autofocus
                    data-cy="SendEmailNotificationDialogInput"
                />
            </QCardSection>
            <QCardActions align="right">
                <QBtn :label="t('globals.cancel')" color="primary" flat v-close-popup />
                <QBtn
                    :label="t('globals.confirm')"
                    color="primary"
                    :loading="isLoading"
                    @click="confirm"
                    unelevated
                />
            </QCardActions>
        </QCard>
    </QDialog>
</template>

<style lang="scss" scoped>
.q-card {
    min-width: 350px;
}
</style>

<i18n>
    es:
        Send email notification: Enviar notificación por correo
        The notification will be sent to the following address: La notificación se enviará a la siguiente dirección
</i18n>
