<template>
  <q-page class="reset-password-page" padding>
    <q-card class="reset-password-card q-pa-lg bg-surface" flat>
      <div class="text-center">
        <q-img
          src="images/kizzo_logo.svg"
          style="max-width: 220px"
        />

        <div
          class="text-weight-regular"
          style="font-size: 20px; letter-spacing: 0.15px"
        >
          Redefinir senha
        </div>
      </div>

      <q-form
        ref="resetPasswordForm"
        autocapitalize="off"
        autocomplete="off"
        autocorrect="off"
        class="q-pa-md"
        spellcheck="false"
        @submit="submitResetPassword"
      >
        <q-card-section class="q-mt-sm flex column q-gutter-y-md">
          <q-banner
            class="bg-primary text-white"
            rounded
          >
            Escolha uma nova senha para concluir a recuperação de acesso.
          </q-banner>

          <q-input
            v-model="email"
            hide-bottom-space
            label="Email"
            lazy-rules
            type="email"
            :rules="[inputRules.required, inputRules.email]"
          />

          <DefaultPasswordInput
            v-model="password"
            hide-bottom-space
            label="Nova senha"
            lazy-rules
            :rules="[inputRules.required, inputRules.min(6)]"
          />

          <DefaultPasswordInput
            v-model="confirmPassword"
            hide-bottom-space
            label="Confirmar nova senha"
            lazy-rules
            :rules="confirmPasswordRules"
          />

          <div class="text-right">
            <span
              class="text-primary cursor-pointer"
              style="font-size: 14px"
              @click="goToLogin"
            >
              Voltar para login
            </span>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="q-px-md q-mt-md">
          <q-btn
            class="full-width"
            color="primary"
            label="Alterar senha"
            size="md"
            style="border-radius: 8px"
            type="submit"
            :loading="submitting"
          >
            <template #loading>
              <q-spinner />
            </template>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { resetForgotPassword } from "src/api/forgotPassword";
import { useInputRules } from "src/composables/useInputRules";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";

import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";

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

const $q = useQuasar();

const { inputRules } = useInputRules();

const email = ref("");
const token = ref("");
const password = ref("");
const confirmPassword = ref("");
const submitting = ref(false);
const resetPasswordForm = ref(null);

const confirmPasswordRules = computed(() => [
  inputRules.required,
  inputRules.samePassword(password.value),
]);

const getQueryValue = (value) => (Array.isArray(value) ? value[0] : value);

const goToLogin = () => {
  router.push({ name: "LoginPage" });
};

const notifyMissingToken = () => {
  $q.notify({
    type: "negative",
    message: "Link de recuperação inválido. Solicite um novo link.",
    position: "top-right",
    timeout: 5000,
  });
};

const submitResetPassword = async () => {
  try {
    submitting.value = true;

    if (!token.value) {
      submitting.value = false;

      notifyMissingToken();

      return;
    }

    const validate = await resetPasswordForm.value.validate();

    if (!validate) {
      submitting.value = false;

      return;
    }

    await resetForgotPassword({
      email: email.value,
      token: token.value,
      password: password.value,
    });

    $q.notify({
      type: "positive",
      message: "Senha alterada com sucesso.",
      position: "top-right",
      timeout: 5000,
    });

    submitting.value = false;

    goToLogin();
  } catch (error) {
    submitting.value = false;

    $q.notify({
      type: "negative",
      message:
        error?.response?.data?.message ||
        "Erro ao alterar senha. Verifique o token e tente novamente.",
      position: "top-right",
      timeout: 5000,
    });
  }
};

onMounted(() => {
  email.value = getQueryValue(route.query.email) || "";
  token.value = getQueryValue(route.query.token) || "";

  if (!token.value) {
    notifyMissingToken();
  }
});
</script>

<style lang="scss" scoped>
.reset-password-page {
  display: flex;
  justify-content: center;
  align-items: center;

  .reset-password-card {
    width: 100%;
    max-width: 600px;
    border-radius: 12px;
    padding-top: 40px;
  }
}
</style>
