<script lang="ts" setup>
import {useAccountStore} from "~/store/account";
import {useNotificationStore} from "~/store/notification";
import type {ApiError} from "~/composables/fetch-api";

definePageMeta({
  layout: 'main-header'
});

const email = ref();
const loading = ref(false);

function sendEmail() {
  loading.value = true;
  useAccountStore()
    .requestPasswordReset(email.value)
    .then(() => {
      useNotificationStore().pushNotification("success",{message: "Consultez vos emails pour réinitialiser votre mot de passe."})
      navigateTo("login");
    })
    .catch((apiError: ApiError) => {
      let details;
      if (apiError.fieldErrors) {
        details = apiError.fieldErrors.map(error => `${error.fields!.join(", ")} ${error.detail}`);
      }
      useNotificationStore().pushNotification("warn",{message: apiError.message, details});
    })
    .finally(() => {
      loading.value = false;
    });
}

</script>

<template>
  <section>
    <h1>Mot de passe oublié</h1>
    <form class="form" @submit.prevent="sendEmail">
      <p>Entrez votre email pour recevoir un lien permettant de réinitialiser le mot de passe associé à votre
        compte.</p>
      <input v-model="email" type="email" placeholder="E-mail" required/>
      <div class="button-container">
        <nuxt-link class="button gray button-back" to="/login" aria-label="Retour à la page de login">❮</nuxt-link>
        <button class="button orange" type="submit">Envoyer l'e-mail</button>
      </div>
      <loader v-if="loading"/>
    </form>
  </section>
</template>

<style lang="scss" scoped>
@import "assets/css/spacing";
.form {
  display: flex;
  flex-direction: column;
  gap: $x_small;
}
</style>
