<script setup lang="ts">
import { ZodError } from 'zod';
import { schema, type Login } from '~/schemas/login';

definePageMeta({
    usersGoesTo: '/user/profile'
});

const state = reactive<Login>({
    usernameOrEmail: '',
    password: ''
});

const { data: result, status, error, refresh } = await useFetch('/api/auth/login', {
    body: state,
    immediate: false,
    method: 'POST',
    watch: false,
    ignoreResponseError: true,
})

const usernameError = ref("");
const passwordError = ref("");
const generalError = ref("");

async function submit()
{
    if(state.password === "")
        return;

    const data = schema.safeParse(state);

    if(data.success)
    {
        await refresh()

        const login = result.value;
        if(!login || !login.success)
        {
            handleErrors(login?.error ?? error.value!);
        }
        else if(status.value === 'success' && login.success)
        {
            await navigateTo('/user/profile');
        }
    }
    else
    {
        handleErrors(data.error);
    }
}
function handleErrors(error: Error | ZodError)
{
    if(error.hasOwnProperty('issues'))
    {
        for(const err of (error as ZodError).issues)
        {
            if(err.path.includes('username'))
            {
                usernameError.value = err.message;
            }
            if(err.path.includes('password'))
            {
                passwordError.value = err.message;
            }
        }
    }
    else
    {
        generalError.value = error?.message ?? 'Erreur inconnue.';
    }
}
</script>

<template>
    <Head>
        <Title>Se connecter</Title>
    </Head>
    <div class="flex flex-1 justify-center items-center">
        <div class="p-8 w-[48em] border border-light-35 dark:border-dark-35">
            <form @submit.prevent="submit" class="p-4 bg-light-25 dark:bg-dark-30">
                <h1 class="text-2xl font-bold tracking-wider pb-4">Connexion</h1>
                <InputField type="text" autocomplete="username" v-model="state.usernameOrEmail"
                    placeholder="" title="Nom d'utilisateur ou adresse mail" :error="usernameError" class="w-[24em]" />
                <InputField type="password" autocomplete="current-password" v-model="state.password"
                    placeholder="" title="Mot de passe"
                    :error="passwordError"  class="w-[24em]"/>
                <span v-if="generalError" class="text-light-red dark:text-dark-red">{{ generalError }}</span>
                <button class="m-auto block px-4 py-1 bg-light-20 dark:bg-dark-20 border border-light-40 dark:border-dark-40 hover:border-light-50 dark:hover:border-dark-50 active:relative active:top-[1px]">
                    <div class="loading" v-if="status === 'pending'"></div>
                    <template v-else>Se connecter</template>
                </button>
                <NuxtLink class="mt-4 text-center block text-sm font-semibold tracking-wide hover:italic" :to="{ path: `/user/register`, force: true }">Pas de compte ?</NuxtLink>
            </form>
        </div>
    </div>
</template>