<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin">
      <DefaultDialogHeader :title="props.title" @close="onDialogCancel" />
      <q-card-section>
        <q-form ref="formRef" class="row q-col-gutter-sm">
          <q-input
            v-model="name"
            label="Nome"
            hint="Nome e sobrenome"
            :rules="[inputRules.required]"
            class="col-6"
          />
          <q-input
            v-model="email"
            label="Email"
            :rules="[inputRules.email]"
            class="col-6"
          />
          <q-input
            v-model="password"
            label="Senha"
            :rules="[inputRules.min(6)]"
            class="col-6"
          />
        </q-form>
      </q-card-section>
      <q-card-actions align="center">
        <q-btn color="primary" label="Cancel" @click="onDialogCancel" />
        <q-space />
        <q-btn color="primary" label="OK" @click="onOKClick" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script setup>
import { ref } from "vue";
import { inputRules } from "src/helpers/utils";
import { useDialogPluginComponent } from "quasar";

import DefaultDialogHeader from "src/components/geral/DefaultDialogHeader.vue";

defineEmits([
  // REQUIRED; need to specify some events that your
  // component will emit through useDialogPluginComponent()
  ...useDialogPluginComponent.emits,
]);

const props = defineProps({
  user: {
    type: Object,
    default: null,
  },
  title: {
    type: Function,
    default: () => "Adicionar Usuário",
  },
});

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

const formRef = ref(null);

const name = ref(props.user?.name || "");
const email = ref(props.user?.email || "");
const password = ref("");

// this is part of our example (so not required)
const onOKClick = () => {
  if (!formRef.value.validate()) {
    return;
  }

  const payload = {
    name: name.value,
    email: email.value,
    password: password.value,
  };
  // on OK, it is REQUIRED to
  // call onDialogOK (with optional payload)
  onDialogOK({ ...payload });
  // or with payload: onDialogOK({ ... })
  // ...and it will also hide the dialog automatically
};
</script>
