<template>
  <q-page class="column justify-center items-center login-page">
    <div
      flat
      class="column justify-center items-center flex-grow full-width z-top bg-background"
      style="
        max-width: 659px;
        max-height: 539px;
        width: 100%;
        height: 100%;
        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="currentStep === 'resend-email' ? currentStep = 'email-data' : $router.back()"
        />
        <span class="text-h6 text-weight-regular">Esqueci minha senha</span>
      </div>

      <EmailDataStep
        v-if="currentStep === 'email-data'"
        :loading
        :email-error="emailError"
        @submit="handleSubmit"
        @clear-error="emailError = ''"
      />

      <ResendEmailStep
        v-else-if="currentStep === 'resend-email'"
        :email
        :loading
        @resend="handleResend"
      />
    </div>
  </q-page>
</template>

<script setup>
import { ref } from "vue";
import EmailDataStep from "./forgot-password/EmailDataStep.vue";
import ResendEmailStep from "./forgot-password/ResendEmailStep.vue";
import { forgotPassword } from "src/api/auth";

const currentStep = ref("email-data");
const email = ref("");
const loading = ref(false);
const emailError = ref("");

async function handleSubmit(submittedEmail) {
  loading.value = true;
  emailError.value = "";
  try {
    await forgotPassword(submittedEmail);
    email.value = submittedEmail;
    currentStep.value = "resend-email";
  } catch (err) {
    if (err.response?.status === 422) {
      emailError.value = err.response.data.message;
    }
  } finally {
    loading.value = false;
  }
}

async function handleResend() {
  loading.value = true;
  try {
    await forgotPassword(email.value);
  } 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>
