<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 800px">
      <DefaultDialogHeader :title="title" @close="onDialogCancel" />
      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultInput
            v-model="form.name"
            v-model:error="validationErrors.name"
            :rules="[inputRules.required]"
            :label="$t('common.terms.name')"
            :placeholder="$t('user.profile.name_and_surname')"
            class="col-md-6 col-12"
          />
          <UserTypeSelect
            v-model="selectedUserType"
            v-model:error="validationErrors.type"
            :rules="[inputRules.required]"
            :type="form.type"
            :label="$t('common.ui.misc.type')"
            :placeholder="'O tipo delimita as permissões'"
            class="col-md-6 col-12"
          />
          <DefaultInput
            v-model="form.email"
            v-model:error="validationErrors.email"
            :rules="[inputRules.email, inputRules.required]"
            label="Email"
            :placeholder="'Ex. email@email.com'"
            class="col-12"
          />
          <DefaultPasswordInput
            v-model="form.password"
            v-model:error="validationErrors.password"
            :rules="
              user
                ? [inputRules.password]
                : [inputRules.required, inputRules.password]
            "
            :label="$t('common.terms.password')"
            :placeholder="'Digite uma senha segura'"
            class="col-md-6 col-12"
          />
          <DefaultPasswordInput
            v-model="confirmPassword"
            :rules="
              user
                ? [inputRules.samePassword(form.password)]
                : [inputRules.required, inputRules.samePassword(form.password)]
            "
            :label="$t('auth.confirm_password')"
            class="col-md-6 col-12"
          />
        </q-card-section>
        <q-card-actions>
          <q-space />
          <q-btn
            outline
            color="negative"
            :label="$t('common.actions.cancel')"
            @click="onDialogCancel"
          />
          <q-btn
            color="primary"
            :label="user ? $t('common.actions.save') : $t('common.actions.add')"
            :type="'submit'"
            :loading="loading"
            :disable="!hasUpdatedFields"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
<script setup>
import { ref, useTemplateRef, watch } from "vue";
import { useInputRules } from "src/composables/useInputRules";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { createUser, updateUser } from "src/api/user";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";
import UserTypeSelect from "src/components/selects/UserTypeSelect.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";

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

const { user, title } = defineProps({
  user: {
    type: Object,
    default: null,
  },
  title: {
    type: Function,
    default: () => useI18n().t("common.terms.title"),
  },
});

const { inputRules } = useInputRules();

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

const formRef = useTemplateRef("formRef");

const { form, getUpdatedFields, hasUpdatedFields } = useFormUpdateTracker({
  name: user ? user?.name : "",
  email: user ? user?.email : "",
  type: user ? user?.type : "",
  password: "",
});

const selectedUserType = ref(null);
const confirmPassword = ref("");

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

const onOKClick = async () => {
  if (user) {
    await submitForm(() => updateUser(getUpdatedFields.value, user.id));
  } else {
    await submitForm(() => createUser({ ...form }));
  }
};

watch(selectedUserType, () => {
  form.type = selectedUserType.value.value;
});
</script>
