<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin column no-wrap" style="width: 800px">
      <DefaultDialogHeader :title="title" @close="onDialogCancel" />
      <q-form ref="formRef" class="full-height scroll" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm">
          <q-input
            v-model="form.name"
            :label="$t('common.terms.name')"
            :hint="$t('user.profile.name_and_surname')"
            :rules="[inputRules.required]"
            :error="!!serverErrors.name"
            :error-message="serverErrors.name"
            class="col-md-6 col-12"
            @update:model-value="serverErrors.name = null"
          />
          <UserTypeSelect
            v-model="selectedUserType"
            :rules="[inputRules.required]"
            :type="form.type"
            :error="!!serverErrors.email"
            :error-message="serverErrors.email"
            class="col-md-6 col-12"
            @update:model-value="serverErrors.email = null"
          />
          <q-input
            v-model="form.email"
            label="Email"
            :rules="[inputRules.email]"
            :error="!!serverErrors.type"
            :error-message="serverErrors.type"
            class="col-12"
            @update:model-value="serverErrors.type = null"
          />
          <DefaultPasswordInput
            v-model="form.password"
            :rules="
              user
                ? [inputRules.password]
                : [inputRules.required, inputRules.password]
            "
            :error="!!serverErrors.password"
            :error-message="serverErrors.password"
            class="col-md-6 col-12"
            @update:model-value="serverErrors.password = null"
          />
          <DefaultPasswordInput
            v-model="confirmPassword"
            :label="$t('auth.confirm_password')"
            :rules="
              user
                ? [inputRules.samePassword(form.password)]
                : [inputRules.required, inputRules.samePassword(form.password)]
            "
            class="col-md-6 col-12"
          />
        </q-card-section>
        <q-card-actions align="center">
          <q-btn color="primary" label="Cancel" @click="onDialogCancel" />
          <q-space />
          <q-btn
            color="primary"
            label="OK"
            :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 "./UserTypeSelect.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,
  serverErrors,
  execute: submitForm,
} = useSubmitHandler(() => onDialogOK(true));

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

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