﻿<template>
  <div>
    <div class="flex flex-col items-center min-w-[300px] m-4">
      <h1 class="text-center text-2xl font-bold mb-5">Connexion</h1>
      <google-login class="w-full" :callback="googleCallback" popup-type="TOKEN">
        <template #default>
          <v-btn density="comfortable" class="mb-2 w-full">
            <v-icon left>mdi-google</v-icon>
            Google
          </v-btn>
        </template>
      </google-login>
      <div class="w-full h-0.5 mt-4 mb-4" :style="{ backgroundColor: '#A30E79' }"></div>
      <v-btn density="comfortable" class="mb-2 w-full" @click="showEmailForm = !showEmailForm">
        <v-icon left>mdi-account</v-icon>
        Utilisateur
      </v-btn>
      <div v-if="showEmailForm" class="w-full mt-2">
        <v-text-field v-model="email" label="Courriel" variant="outlined" dense prepend-inner-icon="mdi-email"
                      color="transparent" class="text-black"></v-text-field>
        <v-text-field v-model="password" label="Mot de passe" :type="showPassword ? 'text' : 'password'"
                      variant="outlined" dense prepend-inner-icon="mdi-lock" append-inner-icon="mdi-eye"
                      @click:append-inner="showPassword = !showPassword" color="transparent"
                      class="text-black"></v-text-field>
        <v-btn class="w-full text-center text-white" :style="{ backgroundColor: '#A30E79' }" @click="login">Connecter
        </v-btn>
        <p class="mt-4 text-sm text-center">Si vous n'avez pas de compte, <a href="/register" class="text-blue-500">cliquez
          ici</a> pour en créer un.</p>
        <div v-if="errorSnackBar" class="mb-4 text-red-600">Nom d'utilisateur ou mot de passe invalide.
          <button class="text-red-600 ml-4" @click="errorSnackBar = false">Fermer</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {useRouter} from 'vue-router';
import {useAuthStore} from '@/stores/authStore.js';
import {GoogleLogin} from "vue3-google-login";

const authStore = useAuthStore();
const router = useRouter();

const email = ref("");
const password = ref("");
const errorSnackBar = ref(false);
const showEmailForm = ref(false);
const showPassword = ref(false);

const props = defineProps({
  onSuccess: {
    type: Function,
    required: true
  },
  onFailure: {
    type: Function,
    required: false
  }
});

async function googleCallback(token) {
  const response = await authStore.loginWithGoogle(JSON.stringify(token));
  handleResponse(response)
}

async function login() {
  const response = await authStore.login(email.value, password.value);
  handleResponse(response)
}

function handleResponse(response) {
  if (response === true) {
    props.onSuccess();
  } else {
    if (props.onFailure) {
      props.onFailure();
    }
    errorSnackBar.value = true;
  }
}

</script>
