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

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

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

const confirmPassword = ref("");

const { status, register } = useAuth();

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("");

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

    if(data.success && state.password !== "" && confirmPassword.value === state.password)
    {
        let errors = await register(data.data.username, data.data.email, data.data.password, {});

        if(status.value === AuthStatus.connected)
        {
            await navigateTo('/');
        }
        else
        {
            errors = errors?.issues ?? errors;
            usernameError.value = errors?.find((e: any) => e.path.includes("username"))?.message ?? "";
            emailError.value = errors?.find((e: any) => e.path.includes("email"))?.message ?? "";
        }
    }
    else
    {
        usernameError.value = data.error?.issues.find(e => e.path.includes("username"))?.message ?? "";
        emailError.value = data.error?.issues.find(e => e.path.includes("email"))?.message ?? "";
    }
}
</script>

<template>

    <Head>
        <Title>S'inscrire</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>Inscription</h1>
                <Input type="text" autocomplete="username" v-model="state.username"
                    placeholder="Entrez un nom d'utiliateur" title="Nom d'utilisateur" :error="usernameError" />
                <Input type="text" autocomplete="email" v-model="state.email" placeholder="Entrez une addresse mail"
                    title="Adresse mail" :error="emailError" />
                <Input type="password" autocomplete="new-password" v-model="state.password"
                    placeholder="Entrez un mot de passe" title="Mot de passe"
                    :error="!(checkedLength && checkedLowerUpper && checkedDigit && checkedSymbol)" />
                <div class="password-validation-group">
                    <span class="password-validation-title">Votre mot de passe doit respecter les critères suivants
                        :</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedLength}">Entre 8 et 128
                        caractères</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedLowerUpper}">Au moins
                        une minuscule et une majuscule</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedDigit}">Au moins un
                        chiffre</span>
                    <span class="password-validation-item" :class="{'validation-error': !checkedSymbol}">Au moins un
                        caractère spécial parmis la liste suivante:
                        <pre>! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre>
                    </span>
                </div>
                <Input type="password" v-model="confirmPassword" placeholder="Confirmer le mot de passe"
                    title="Confirmer le mot de passe"
                    :error="confirmPassword === '' || confirmPassword === state.password ? '' : 'Les mots de passe saisies ne sont pas identique'" />
                <button>S'inscrire</button>
                <NuxtLink to="/user/login">Se connecter</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>