<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin dialog-form-card"
      style="width: 800px"
    >
      <DefaultDialogHeader
        :title="title"
        @close="onDialogCancel"
      />

      <DefaultForm
        ref="formRef"
        @submit="onOKClick"
      >
        <q-scroll-area class="dialog-form-scroll dialog-form-scroll--sm">
          <q-card-section class="row q-col-gutter-sm q-pt-none">
            <DefaultInput
              v-model="form.name"
              class="col-md-6 col-12"
              :error="!!validationErrors.name"
              :error-message="validationErrors.name"
              :label="$t('common.terms.name')"
              :placeholder="$t('user.profile.name_and_surname')"
              :rules="[inputRules.required]"
            />

            <UserTypeSelect
              v-model="selectedUserType"
              class="col-md-6 col-12"
              :error="!!validationErrors.type"
              :error-message="validationErrors.type"
              :label="$t('common.ui.misc.type')"
              :placeholder="'O tipo delimita as permissões'"
              :rules="[inputRules.required]"
              :type="form.type"
            />

            <DefaultInput
              v-model="form.email"
              class="col-12"
              label="Email"
              :error="!!validationErrors.email"
              :error-message="validationErrors.email"
              :placeholder="'Ex. email@email.com'"
              :rules="[
                inputRules.email,
                inputRules.required,
              ]"
            />

            <DefaultPasswordInput
              v-model="form.password"
              class="col-md-6 col-12"
              :error="!!validationErrors.password"
              :error-message="validationErrors.password"
              :label="$t('common.terms.password')"
              :placeholder="'Digite uma senha segura'"
              :rules="
                user
                  ? [inputRules.password]
                  : [
                      inputRules.required,
                      inputRules.password,
                    ]
              "
            />

            <DefaultPasswordInput
              v-model="confirmPassword"
              class="col-md-6 col-12"
              :error="!!validationErrors.password_confirmation"
              :error-message="
                validationErrors.password_confirmation
              "
              :label="$t('auth.confirm_password')"
              :rules="
                user
                  ? [
                      inputRules.samePassword(
                        form.password,
                      ),
                    ]
                  : [
                      inputRules.required,
                      inputRules.samePassword(
                        form.password,
                      ),
                    ]
              "
            />
          </q-card-section>
        </q-scroll-area>

        <q-card-actions
          align="right"
          class="q-px-md q-pb-md"
        >
          <q-btn
            color="primary"
            no-caps
            outline
            :label="$t('common.actions.cancel')"
            @click="onDialogCancel"
          />

          <q-btn
            color="primary"
            no-caps
            type="submit"
            :disable="!hasUpdatedFields"
            :label="
              user
                ? $t('common.actions.save')
                : $t('common.actions.add')
            "
            :loading="loading"
          />
        </q-card-actions>
      </DefaultForm>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { createUser, updateUser } from "src/api/user";
import { ref, useTemplateRef, watch } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useForm } from "src/composables/useForm";
import { useI18n } from "vue-i18n";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import UserTypeSelect from "src/components/selects/UserTypeSelect.vue";

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

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

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

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

const { inputRules } = useInputRules();

const formRef = useTemplateRef("formRef");

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

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

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

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

    return;
  }

  await submitForm(() =>
    createUser({ ...form }),
  );
};

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