<template>
    <Head>
        <Title>d[any] - Inscription</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 dark:hover: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>
            <ProseH4>Inscription</ProseH4>
        </div>
        <form @submit.prevent="() => submit()" class="grid flex-1 p-4 grid-cols-2 md:grid-cols-1 gap-4 md:gap-0">
            <TextInput type="text" label="Nom d'utilisateur" name="username" autocomplete="username" v-model="state.username" class="w-full md:w-auto"/>
            <TextInput type="email" label="Email" name="email" autocomplete="email" v-model="state.email" class="w-full md:w-auto"/>
            <TextInput type="password" label="Mot de passe" name="password" autocomplete="new-password" v-model="state.password" class="w-full md:w-auto"/>
            <div class="grid grid-cols-2 flex-col font-light border border-light-35 dark:border-dark-35 px-4 py-2 m-4 ms-0 text-sm leading-[18px] lg:text-base order-8 col-span-2 md:col-span-1 md:order-none">
                <span class="col-span-2">Prérequis de sécurité</span>
                <span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedLength}"><Icon v-show="!checkedLength" icon="radix-icons:cross-2" />8 à 128 caractères</span>
                <span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedLower}"><Icon v-show="!checkedLower" icon="radix-icons:cross-2" />Une minuscule</span>
                <span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedUpper}"><Icon v-show="!checkedUpper" icon="radix-icons:cross-2" />Une majuscule</span>
                <span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedDigit}"><Icon v-show="!checkedDigit" icon="radix-icons:cross-2" />Un chiffre</span>
                <span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedSymbol}"><Icon v-show="!checkedSymbol" icon="radix-icons:cross-2" />Un caractère special</span>
            </div>
            <TextInput type="password" label="Confirmation du mot de passe" autocomplete="new-password" v-model="confirmPassword" class="w-full md:w-auto"/>
            <Button type="submit" class="border border-light-35 dark:border-dark-35 max-w-48 w-full order-9 col-span-2 md:col-span-1 m-auto" :loading="status === 'pending'">S'inscrire</Button>
            <span class="mt-4 order-10 flex justify-center items-center gap-4 col-span-2 md:col-span-1 m-auto">Vous avez déjà un compte ?<NuxtLink class="text-center block text-sm font-semibold tracking-wide hover:text-accent-blue" :to="{ name: 'user-login' }">Se connecter</NuxtLink></span>
        </form>
    </div>
</template>

<script setup lang="ts">
import { ZodError } from 'zod';
import { schema, type Registration } from '~/schemas/registration';
import { Icon } from '@iconify/vue/dist/iconify.js';

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

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

const { add: addToast, clear: clearToasts } = useToast();
const confirmPassword = ref("");

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

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

async function submit()
{
    if(state.username === '')
        return addToast({ content: 'Veuillez saisir un nom d\'utilisateur', timer: true, duration: 10000 });
    if(state.email === '')
        return addToast({ content: 'Veuillez saisir une adresse mail', timer: true, duration: 10000 });
    if(state.password === "")
        return addToast({ content: 'Veuillez saisir un mot de passe', timer: true, duration: 10000 });
    if(state.password !== confirmPassword.value)
        return addToast({ content: 'Les deux mots de passe saisis ne correspondent pas', 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)
        {
            clearToasts();
            addToast({ duration: 10000, content: 'Vous avez été enregistré. Pensez à valider votre adresse mail.', timer: true, type: 'success' });
            await navigateTo('/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 addToast({ content: err.message, timer: true, duration: 10000, type: 'error' });
        }
    }
    else
    {
        return addToast({ content: error?.message ?? 'Une erreur est survenue', timer: true, duration: 10000, type: 'error' });
    }
}
</script>