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

import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModel from 'components/FormModel.vue';

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

const $props = defineProps({
    parentId: {
        type: Number,
        default: null,
    },
});

const { t } = useI18n();

const departmentChildData = reactive({
    name: null,
});

const closeButton = ref(null);
const isLoading = ref(false);

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

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

onMounted(() => {
    if ($props.parentId) departmentChildData.parentId = $props.parentId;
});
</script>

<template>
    <FormModel
        model="createDepartmentChild"
        :form-initial-data="departmentChildData"
        :observe-form-changes="false"
        :default-actions="false"
        url-create="departments/createChild"
        @on-data-saved="onDataSaved()"
    >
        <template #form="{ data }">
            <span ref="closeButton" class="close-icon" v-close-popup>
                <QIcon name="close" size="sm" />
            </span>
            <h1 class="title">{{ t('New department') }}</h1>
            <VnRow class="row q-gutter-md q-mb-md" style="min-width: 250px">
                <VnInput :label="t('Name')" v-model="data.name" />
            </VnRow>
            <div class="q-mt-lg row justify-end">
                <QBtn
                    :label="t('globals.cancel')"
                    type="reset"
                    color="primary"
                    flat
                    class="q-ml-sm"
                    :disabled="isLoading"
                    :loading="isLoading"
                    v-close-popup
                />
                <QBtn
                    :label="t('globals.save')"
                    type="submit"
                    color="primary"
                    :disabled="isLoading"
                    :loading="isLoading"
                />
            </div>
        </template>
    </FormModel>
</template>

<style lang="scss" scoped>
.close-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    cursor: pointer;
}
.title {
    font-size: 17px;
    font-weight: bold;
    line-height: 20px;
}
</style>

<i18n>
es:
    Name: Nombre
    New department: Nuevo departamento
</i18n>
