<template>
  <q-page class="q-pa-md">
    <SettingsTabsHeader />

    <q-card bordered class="settings-card" flat>
      <q-card-section class="q-pb-none">
        <div class="text-h6 text-weight-bold">
          {{
            isEditMode
              ? $t("settings.users.edit_title")
              : $t("settings.users.create_title")
          }}
        </div>

        <div class="text-grey-7 q-mt-xs">
          {{ $t("settings.users.form_description") }}
        </div>
      </q-card-section>

      <q-card-section class="q-pt-lg">
        <div class="row q-col-gutter-lg">
          <q-input
            v-model="form.name"
            class="col-12 col-md-6"
            :error="!!serverErrors.name"
            :error-message="serverErrors.name"
            :label="$t('common.terms.name')"
          />

          <q-input
            v-model="form.email"
            class="col-12 col-md-6"
            type="email"
            :error="!!serverErrors.email"
            :error-message="serverErrors.email"
            :label="$t('common.terms.email')"
          />

          <q-select
            v-model="form.user_type_id"
            class="col-12 col-md-6"
            emit-value
            map-options
            :error="!!serverErrors.user_type_id"
            :error-message="serverErrors.user_type_id"
            :label="$t('settings.user_types.single')"
            :options="userTypeOptions"
          />

          <q-input
            v-model="form.password"
            class="col-12 col-md-6"
            type="password"
            :error="!!serverErrors.password"
            :error-message="serverErrors.password"
            :hint="
              isEditMode ? $t('settings.users.password_optional_hint') : ''
            "
            :label="$t('common.terms.password')"
          />
        </div>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right" class="q-pa-lg">
        <q-btn
          color="primary"
          outline
          padding="10px 24px"
          :label="$t('common.actions.cancel')"
          @click="router.push({ name: 'SettingsUsersPage' })"
        />

        <q-btn
          class="btn-custom-default"
          color="secondary"
          padding="10px 28px"
          :disable="isSaveDisabled"
          :loading="loading"
          @click="onSubmit"
        >
          <span class="text-primary">{{ $t("common.actions.save") }}</span>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { createUser, getUserById, updateUser, userTypes } from "src/api/user";
import { normalizeUserTypeOptions } from "./utils";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import SettingsTabsHeader from "./components/SettingsTabsHeader.vue";

const route  = useRoute();
const router = useRouter();

const { t } = useI18n();

const { execute, loading, serverErrors } = useSubmitHandler(() => {
  router.push({ name: "SettingsUsersPage" });
});

const { form, getUpdatedFields, hasUpdatedFields, setUpdateFormAsOriginal } =
  useFormUpdateTracker({
    name:         "",
    email:        "",
    password:     "",
    user_type_id: null,
  });

const userTypeOptions = ref([]);

const isEditMode = computed(() => !!route.params.id);

const isSaveDisabled = computed(() => {
  if (!isEditMode.value) {
    return !form.name || !form.email || !form.password || !form.user_type_id;
  }

  return !hasUpdatedFields.value;
});

const fetchUserTypeOptions = async () => {
  const response = await userTypes();
  userTypeOptions.value = normalizeUserTypeOptions(response, t);
};

const fetchUser = async () => {
  const response = await getUserById(route.params.id);

  form.name         = response.name  || "";
  form.email        = response.email || "";
  form.password     = "";
  form.user_type_id = Number(response.user_type?.value || response.user_type_id);

  setUpdateFormAsOriginal();
};

const sanitizePayload = (payload) => {
  const nextPayload = { ...payload };

  Object.keys(nextPayload).forEach((key) => {
    if (
      nextPayload[key] === null      ||
      nextPayload[key] === undefined ||
      nextPayload[key] === ""
    ) {
      delete nextPayload[key];
    }
  });

  return nextPayload;
};

const onSubmit = async () => {
  const payload = sanitizePayload(
    isEditMode.value ? getUpdatedFields.value : form,
  );

  await execute(async () => {
    if (isEditMode.value) {
      return await updateUser(payload, route.params.id);
    }

    return await createUser(payload);
  });
};

onMounted(async () => {
  await fetchUserTypeOptions();

  if (isEditMode.value) {
    await fetchUser();
  }
});
</script>

<style scoped lang="scss">
.settings-card {
  border-radius: 18px;
}
</style>
