<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, Boolean],
        default: null,
    },
    data: {
        type: Object,
        required: false,
        default: null,
    },
    promise: {
        type: Function,
        required: false,
        default: null,
    },
});

defineEmits(['confirm', ...useDialogPluginComponent.emits]);
defineExpose({ show: () => dialogRef.value.show(), hide: () => dialogRef.value.hide() });

const { dialogRef, onDialogOK } = useDialogPluginComponent();

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

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">{{ title }}</span>
                <QSpace />
                <QBtn icon="close" :disable="isLoading" flat round dense v-close-popup />
            </QCardSection>
            <QCardSection class="q-pb-none">
                <span v-if="message !== false" v-html="message" />
            </QCardSection>
            <QCardSection class="row items-center q-pt-none">
                <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>
