<script lang="ts" setup>

import {useAccountStore} from "~/store/account";
import {useNotificationStore} from "~/store/notification";
import {useAuthStore} from "~/store/auth";
import type {ApiError} from "~/composables/fetch-api";

const email = ref(useAuthStore().user.email);
const username = ref(useAuthStore().user.username);
const emailConfirmation = ref();

function updateAccount() {
  if (emailConfirmation.value !== email.value) {
    useNotificationStore().pushNotification("warn", {message: "Saisir le même e-mail dans les champs 'E-mail' et 'Confirmation de l'e-mail'."});
  } else {
    useAccountStore().update(username.value, email.value)
      .then(async () => {
        if (useAuthStore().user.email !== email.value) {
          await useAuthStore().refreshSession();
        }
        useNotificationStore().pushNotification("success", {message: "Votre compte a bien été mis à jour."});
        useAuthStore().user.username = username.value;
        navigateTo("/bundle");
      })
      .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});
      });
  }
}

</script>
<template>
  <div>
    <section>
      <h1>Mon compte</h1>
      <form class="form" @submit.prevent="updateAccount">
        <label for="username">Nom de l'équipe *</label>
        <input id="username" v-model="username" type="text" autocomplete="username" required>
        <label for="email">E-mail *</label>
        <input id="email" v-model="email" type="email" autocomplete="email" required>
        <label for="emailConfirmation">Confirmation de l'e-mail *</label>
        <input id="emailConfirmation" v-model="emailConfirmation" type="email" required>
        <button class="button orange" type="submit">Enregistrer</button>
      </form>
      <div class="button-container">
        <button class="button gray button-back" @click="useRouter().back()" aria-label="Retour à la page précédente">❮
        </button>
        <nuxt-link to="/account/password" class="button blue" type="submit">Modifier mon mot de passe</nuxt-link>
      </div>
    </section>
  </div>
</template>

<style lang="scss" scoped>
@import "assets/css/spacing";

.form {
  & [type="submit"] {
    grid-column: span 2 / 3;
    margin-top: $small;
  }

}
</style>
