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

definePageMeta({
    auth: {
        disconnectedOnly: true,
        connectedRedirect: '/user/profile'
    }
});

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

const { status, login } = useAuth();

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

async function submit()
{
    const data = schema.safeParse(state);

    if(data.success && state.password !== "")
    {
        let errors = await login(data.data.username, data.data.password);

        if(status.value === AuthStatus.connected)
        {
            await navigateTo('/user/profile', { replace: true });
        }
        else
        {
            errors = errors?.issues ?? errors;
            usernameError.value = errors?.find((e: any) => e.path.includes("username"))?.message ?? "";
            passwordError.value = errors?.find((e: any) => e.path.includes("password"))?.message ?? "";
        }
    }
    else
    {
        usernameError.value = data.error?.issues.find(e => e.path.includes("username"))?.message ?? "";
        passwordError.value = data.error?.issues.find(e => e.path.includes("password"))?.message ?? "";
    }
}
</script>

<template>
    <Head>
        <Title>Se connecter</Title>
    </Head>
    <div class="site-body-center-column">
        <div class="render-container flex align-center justify-center">
            <form v-if="status === AuthStatus.disconnected" @submit.prevent="submit" class="input-form input-form-wide">
                <h1>Connexion</h1>
                <Input type="text" autocomplete="username" v-model="state.username"
                    placeholder="" title="Nom d'utilisateur ou adresse mail" :error="usernameError" />
                <Input type="password" autocomplete="current-password" v-model="state.password"
                    placeholder="" title="Mot de passe"
                    :error="passwordError" />
                <button>Se connecter</button>
                <NuxtLink to="/user/register">Pas de compte ?</NuxtLink>
            </form>
            <div v-else-if="status === AuthStatus.loading" class="input-form"><div class="loading"></div></div>
            <div v-else class="not-found-container">
                <div class="not-found-title">👀 Vous n'avez rien à faire ici. 👀</div>
            </div>
        </div>
    </div>
</template>