<template>
    <Head>
        <Title>d[any] - Connexion</Title>
    </Head>
    <div class="flex flex-1 flex-col justify-center items-center">
        <div class="flex gap-8 items-center">
            <span class="border border-transparent hover:border-light-35 hover:dark:border-dark-35 p-1 cursor-pointer" @click="() => $router.go(-1)"><Icon icon="radix-icons:arrow-left" class="text-light-50 dark:text-dark-50 w-6 h-6"/></span>
            <h4 class="text-xl font-bold">Connexion</h4>
        </div>
        <form @submit.prevent="submit" class="flex flex-1 flex-col justify-center items-stretch">
            <TextInput type="text" label="Utilisateur ou email" name="username" autocomplete="username email" v-model="state.usernameOrEmail"/>
            <TextInput type="password" label="Mot de passe" name="password" autocomplete="current-password" v-model="state.password"/>
            <Button type="submit" class="border border-light-35 dark:border-dark-35 self-center" :loading="status === 'pending'">Se connecter</Button>
            <NuxtLink class="mt-4 text-center block text-sm font-semibold tracking-wide hover:text-accent-blue" :to="{ name: 'user-reset-password' }">Mot de passe oublié ?</NuxtLink>
            <NuxtLink class="mt-4 text-center block text-sm font-semibold tracking-wide hover:text-accent-blue" :to="{ name: 'user-register' }">Pas de compte ?</NuxtLink>
        </form>
    </div>
</template>

<script setup lang="ts">
import type { ZodError } from 'zod/v4';
import { schema, type Login } from '~/schemas/login';
import { Icon } from '@iconify/vue';
import { Toaster } from '~~/shared/components';

definePageMeta({
    layout: 'login',
    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,
})

async function submit()
{
    if(state.usernameOrEmail === "")
        return Toaster.add({ content: 'Veuillez saisir un nom d\'utilisateur ou un email', timer: true, duration: 10000 });
    if(state.password === "")
        return Toaster.add({ content: 'Veuillez saisir un mot de passe', timer: true, duration: 10000 });

    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)
        {
            Toaster.clear();
            Toaster.add({ duration: 10000, content: 'Vous êtes maintenant connecté', timer: true, type: 'success' });

            const router = useRouter();
            const target = router.currentRoute.value.query?.t as string | undefined;
            router.push(target ? decodeURIComponent(target) : { name: 'user-profile' });
        }
    }
    else
    {
        handleErrors(data.error);
    }
}
function handleErrors(error: Error | ZodError)
{
    if(!error)
        return;
    
    status.value = 'error';

    if(error.hasOwnProperty('issues'))
    {
        for(const err of (error as ZodError).issues)
        {
            return Toaster.add({ content: err.message, timer: true, duration: 10000, type: 'error' });
        }
    }
    else
    {
        return Toaster.add({ content: error?.message ?? 'Une erreur est survenue', timer: true, duration: 10000, type: 'error' });
    }
}
</script>