<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="min-width: 400px">
      <DefaultDialogHeader title="Novo Tipo de Usuário" @close="onDialogCancel" />

      <q-form ref="formRef" @submit="onSave">
        <q-card-section>
          <DefaultInput
            v-model="form.label"
            label="Nome"
            outlined
            autofocus
            :rules="[inputRules.required]"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            label="Cancelar"
            color="primary"
            outline
            @click="onDialogCancel"
          />
          <q-btn
            label="Salvar"
            color="primary"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, useTemplateRef } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { createUserType } from "src/api/user_type";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const { inputRules } = useInputRules();
const formRef = useTemplateRef("formRef");

const form = ref({ label: "" });

const { loading, execute } = useSubmitHandler({
  formRef,
  onSuccess: () => onDialogOK(),
});

const onSave = async () => {
  await execute(() => createUserType({ label: form.value.label }));
};
</script>
