<template>
  <q-page class="column justify-center items-center login-page">
    <div
      flat
      class="column justify-center items-center full-width z-top bg-background q-py-xl"
      style="max-width: 659px; border-radius: 15px;"
    >
      <div class="flex full-width q-gutter-x-sm items-center q-mb-xl">
        <q-icon
          name="mdi-arrow-left"
          size="sm"
          color="primary"
          @click="handleBack"
        />
        <span class="text-h6 text-weight-regular">Recuperar senha</span>
      </div>

      <VerifyCodeStep
        v-if="currentStep === 'verify-code'"
        :loading
        @submit="handleVerify"
        @resend="handleResend"
      />

      <NewPasswordStep
        v-else-if="currentStep === 'new-password'"
        :loading
        @submit="handleReset"
      />
    </div>
  </q-page>
</template>

<script setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import VerifyCodeStep from "./forgot-password/VerifyCodeStep.vue";
import NewPasswordStep from "./forgot-password/NewPasswordStep.vue";
import { forgotPassword, verifyPasswordCode, resetPassword } from "src/api/auth";

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

const email = route.query.email ?? "";
const currentStep = ref("verify-code");
const verifiedCode = ref("");
const loading = ref(false);

function handleBack() {
  if (currentStep.value === "new-password") {
    currentStep.value = "verify-code";
  } else {
    router.push("/forgot-my-password");
  }
}

async function handleVerify(code) {
  loading.value = true;
  try {
    await verifyPasswordCode(email, code);
    verifiedCode.value = code;
    await new Promise((resolve) => setTimeout(resolve, 3000));
    currentStep.value = "new-password";
  } finally {
    loading.value = false;
  }
}

async function handleResend() {
  loading.value = true;
  try {
    await forgotPassword(email);
  } finally {
    loading.value = false;
  }
}

async function handleReset({ password, passwordConfirmation }) {
  loading.value = true;
  try {
    await resetPassword(email, verifiedCode.value, password, passwordConfirmation);
    router.push("/login");
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  background-image: url("background.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
</style>
