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

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

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

const confirmPassword = ref("");

const checkedLength = computed(() => state.password.length >= 8 && state.password.length <= 128);
const checkedLowerUpper = computed(() => state.password.toLowerCase() !== state.password && state.password.toUpperCase() !== state.password);
const checkedDigit = computed(() => /[0-9]/.test(state.password));
const checkedSymbol = computed(() => " !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~".split("").some(e => state.password.includes(e)));

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

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

async function submit()
{
    if(state.password === "" || state.password !== confirmPassword.value)
        return;

    const data = schema.safeParse(state);

    if(data.success)
    {
        await execute()

        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('email'))
            {
                emailError.value = err.message;
            }
        }
    }
    else
    {
        generalError.value = error?.message ?? 'Erreur inconnue.';
    }
}
</script>

<template>

    <Head>
        <Title>S'inscrire</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">Inscription</h1>
                <InputField type="text" autocomplete="username" v-model="state.username"
                    placeholder="Entrez un nom d'utilisateur" title="Nom d'utilisateur" :error="usernameError" class="w-[24em]"/>
                <InputField type="text" autocomplete="email" v-model="state.email" placeholder="Entrez une addresse mail"
                    title="Adresse mail" :error="emailError"  class="w-[24em]"/>
                <InputField type="password" autocomplete="new-password" v-model="state.password"
                    placeholder="Entrez un mot de passe" title="Mot de passe"
                    :error="!(checkedLength && checkedLowerUpper && checkedDigit && checkedSymbol)"  class="w-[24em]"/>
                <div class="flex flex-col font-light">
                    <span class="">Votre mot de passe doit respecter les critères de sécurité suivants
                        :</span>
                    <span class="px-4" :class="{'text-light-red dark:text-dark-red': !checkedLength}">Entre 8 et 128
                        caractères</span>
                    <span class="px-4" :class="{'text-light-red dark:text-dark-red': !checkedLowerUpper}">Au moins
                        une minuscule et une majuscule</span>
                    <span class="px-4" :class="{'text-light-red dark:text-dark-red': !checkedDigit}">Au moins un
                        chiffre</span>
                    <span class="px-4" :class="{'text-light-red dark:text-dark-red': !checkedSymbol}">Au moins un
                        caractère spécial parmis la liste suivante:
                        <pre>! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre>
                    </span>
                </div>
                <InputField type="password" v-model="confirmPassword" placeholder="Confirmer le mot de passe"
                    title="Confirmer le mot de passe"
                    autocomplete="new-password"
                    :error="confirmPassword === '' || confirmPassword === state.password ? '' : 'Les mots de passe saisies ne sont pas identique'" 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 v-if="status === 'pending'" class="loading"></div><template v-else>S'inscrire</template></button>
                <NuxtLink class="mt-4 text-center block text-sm font-semibold tracking-wide hover:italic" :to="{ path: `/user/login`, force: true }">Vous avez déjà un compte ? Se connecter</NuxtLink>
            </form>
        </div>
    </div>
</template>