<script setup lang="ts">
definePageMeta({
  public: true, pageId: 'login'
})
const localePath = useLocalePath()
const authStore = useAuthStore() // Store authenticate
const login = ref('')
const password = ref('')
const awaiting = ref(false)
const displayPwdReset=true

const errors = ref({
  loginEmpty: false,
  passwordEmpty: false,
  loginFailed: false,
  unconfirmedUser: false,
}) 

const handleFormSubmit = async() => {
  // On retire l'erreur précédente
  errors.value.loginFailed = false;
  errors.value.unconfirmedUser = false;
  awaiting.value = true

  // --- Vérification des données du formulaire --- //
  // En version raccourcie : on stocke le résultat de la condition dans la variable
  errors.value.loginEmpty    = ( login.value    == "" );
  errors.value.passwordEmpty = ( password.value == "" );

  // Si une erreur est rencontrée, on n'envoi pas la requete au serveur
  if( !errors.value.loginEmpty && !errors.value.passwordEmpty )
  {

    // Envoie de la requette à l'endpoint JWT et récupération d'un token de connexion
      const success = await authStore.login(login.value, password.value)
      if (success) {
        // Redirection
        await navigateTo(localePath('/lists'))
      }

      else{
        errors.value.loginFailed = true;
        awaiting.value = false
      }
  }
  else{
    awaiting.value = false
  }
}    
</script>

<template>
  <section>
    <h1>{{$t('loginTitle')}}</h1>
    <form @submit.prevent="handleFormSubmit">
      <InputText
        name="login"
        :label="$t('loginLabelUser')"
        placeholder=""
        v-model="login"
        >
        <template #message>
          <p v-if="errors.loginEmpty" class="error">{{$t('loginErrorLoginEmpty')}}</p>
        </template>
      </InputText>
      
      <InputPassword
      name="password"
      :label="$t('loginLabelPwd')"
      placeholder=""
      v-model="password"
      displayPwdReset
      >
        <template #message>
          <p v-if="errors.passwordEmpty" class="error">{{ $t('loginErrorPwdEmpty') }}</p>
        </template>
      </InputPassword>

      <div class="connection-error" >
        <p v-if="errors.loginFailed">{{ $t('loginErrorLoginFailed') }}</p>
        <p v-if="errors.unconfirmedUser">{{ $t('loginErrorUnconfirmedUSer') }}</p>
      </div>
      <ButtonBase
        :disabled="login === '' || password === '' || awaiting"
        :loading="awaiting"
      >
        {{ $t('loginFormBtn') }}
      </ButtonBase>
    </form>
    <p>{{ $t('loginGoogle') }}</p>
    <ButtonGoogleCode/>

  </section>
</template>

<style lang="scss" scoped>

form {
  display: flex;
  flex-direction: column;
  padding: 1em;
  margin: 0;
}

.connection-error{
  height:1.2em;
  & > p{
    font-weight: bold;
    text-align: center;
    color: rgb(185, 0, 0);
  }
}
</style>