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

const { t } = useI18n();

const props = defineProps({
    icon: {
        type: String,
        default: null,
    },
    title: {
        type: String,
        default: null,
    },
    message: {
        type: String,
        default: null,
    },
    data: {
        type: Object,
        required: false,
        default: null,
    },
    promise: {
        type: Function,
        required: false,
        default: null,
    },
});

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

const { dialogRef, onDialogOK } = useDialogPluginComponent();

const title = props.title || t('Confirm');
const message = props.message || t('Are you sure you want to continue?');
const isLoading = ref(false);

async function confirm() {
    isLoading.value = true;
    if (props.promise) {
        try {
            await props.promise(props.data);
        } finally {
            isLoading.value = false;
        }
    }
    onDialogOK(props.data);
}
</script>
<template>
    <QDialog ref="dialogRef">
        <QCard class="q-pa-sm">
            <QCardSection class="row items-center q-pb-none">
                <QAvatar
                    :icon="icon"
                    color="primary"
                    text-color="white"
                    size="xl"
                    v-if="icon"
                />
                <span class="text-h6 text-grey">{{ title }}</span>
                <QSpace />
                <QBtn icon="close" :disable="isLoading" flat round dense v-close-popup />
            </QCardSection>
            <QCardSection class="row items-center">
                <span v-html="message"></span>
                <slot name="customHTML"></slot>
            </QCardSection>
            <QCardActions align="right">
                <QBtn
                    :label="t('globals.cancel')"
                    color="primary"
                    :disable="isLoading"
                    flat
                    v-close-popup
                />
                <QBtn
                    :label="t('globals.confirm')"
                    color="primary"
                    :loading="isLoading"
                    @click="confirm()"
                    unelevated
                    autofocus
                />
            </QCardActions>
        </QCard>
    </QDialog>
</template>

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

<i18n>
es:
    Confirm: Confirmar
    Are you sure you want to continue?: ¿Seguro que quieres continuar?
</i18n>
