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

import FormModel from 'components/FormModel.vue';

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

const $props = defineProps({
    title: {
        type: String,
        default: '',
    },
    subtitle: {
        type: String,
        default: '',
    },
    url: {
        type: String,
        default: '',
    },
    model: {
        type: String,
        default: '',
    },
    filter: {
        type: Object,
        default: null,
    },
    urlCreate: {
        type: String,
        default: null,
    },
    formInitialData: {
        type: Object,
        default: () => {},
    },
});

const { t } = useI18n();

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

const onDataSaved = (formData, requestResponse) => {
    emit('onDataSaved', formData, requestResponse);
    closeForm();
};

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

const closeForm = async () => {
    if (closeButton.value) closeButton.value.click();
};

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

<template>
    <FormModel
        ref="formModelRef"
        :form-initial-data="formInitialData"
        :observe-form-changes="false"
        :default-actions="false"
        :url-create="urlCreate"
        :model="model"
        @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.save')"
                    type="submit"
                    color="primary"
                    :disabled="isLoading"
                    :loading="isLoading"
                />
                <QBtn
                    :label="t('globals.cancel')"
                    type="reset"
                    color="primary"
                    flat
                    class="q-ml-sm"
                    :disabled="isLoading"
                    :loading="isLoading"
                    v-close-popup
                />
            </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>
