<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';

import FormModel from 'components/FormModel.vue';

const emit = defineEmits(['onDataSaved', 'onDataCanceled']);

defineProps({
    title: {
        type: String,
        default: '',
    },
    subtitle: {
        type: String,
        default: '',
    },
});

const { t } = useI18n();

const formModelRef = ref(null);
const closeButton = ref(null);

const onDataSaved = (formData, requestResponse) => {
    if (closeButton.value) closeButton.value.click();
    emit('onDataSaved', formData, requestResponse);
};

const isLoading = computed(() => formModelRef.value?.isLoading);

defineExpose({
    isLoading,
    onDataSaved,
});
</script>

<template>
    <FormModel
        ref="formModelRef"
        :observe-form-changes="false"
        :default-actions="false"
        v-bind="$attrs"
        @on-data-saved="onDataSaved"
    >
        <template #form="{ data, validate }">
            <span ref="closeButton" class="close-icon" v-close-popup>
                <QIcon name="close" size="sm" />
            </span>
            <h1 class="title">{{ title }}</h1>
            <p>{{ subtitle }}</p>
            <slot name="form-inputs" :data="data" :validate="validate" />
            <div class="q-mt-lg row justify-end">
                <QBtn
                    :label="t('globals.cancel')"
                    :title="t('globals.cancel')"
                    type="reset"
                    color="primary"
                    flat
                    :disabled="isLoading"
                    :loading="isLoading"
                    @click="emit('onDataCanceled')"
                    v-close-popup
                />
                <QBtn
                    :label="t('globals.save')"
                    :title="t('globals.save')"
                    type="submit"
                    color="primary"
                    class="q-ml-sm"
                    :disabled="isLoading"
                    :loading="isLoading"
                />
            </div>
        </template>
    </FormModel>
</template>

<style lang="scss" scoped>
.title {
    font-size: 17px;
    font-weight: bold;
    line-height: 20px;
}

.close-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    cursor: pointer;
}
</style>
