<script setup lang="ts">
import characterConfig from '#shared/character-config.json';
import { Icon } from '@iconify/vue/dist/iconify.js';
import { CharacterBuilder, defaultCharacter } from '~/shared/character';
import type { Character, CharacterConfig } from '~/types/character';

const stepTexts: Record<number, string> = {
    0: 'Choisissez un peuple afin de définir la progression de votre personnage au fil des niveaux.',
    1: 'Déterminez la progression de votre personnage en choisissant une option par niveau disponible.',
    2: 'Spécialisez votre personnage en attribuant vos points d\'entrainement parmi les 7 branches disponibles.\nChaque paliers de 3 points augmentent votre modifieur.',
    3: 'Diversifiez vos possibilités en affectant vos points dans les différentes compétences disponibles.',
    4: 'Déterminez l\'Aspect qui vous corresponds et benéficiez de puissants bonus.'
};

definePageMeta({
    guestsGoesTo: '/user/login',
});
let id = useRouter().currentRoute.value.params.id;
const { add } = useToast();
const config = characterConfig as CharacterConfig;
const data = ref<Character>({ ...defaultCharacter });
const builder = markRaw(new CharacterBuilder(data.value));

const step = ref(0);

if(id !== 'new')
{
    const character = await useRequestFetch()(`/api/character/${id}`);

    if(!character)
    {
        throw new Error('Donnée du personnage introuvables');
    }

    data.value = Object.assign(defaultCharacter, data.value, character);
}

async function save(leave: boolean)
{
    if(data.value.name === '' || data.value.people === undefined || data.value.people === -1)
    {                
        add({ title: 'Données manquantes', content: "Merci de saisir un nom et une race avant de pouvoir enregistrer votre personnage", type: 'error', duration: 25000, timer: true });
        return;
    }
    if(id === 'new')
    {
        //@ts-ignore
        id = await useRequestFetch()(`/api/character`, {
            method: 'post',
            body: data.value,
            onResponseError: (e) => {
                add({ title: 'Erreur d\'enregistrement', content: e.response.status === 401 ? "Vous n'êtes pas autorisé à effectué cette opération" : e.response.statusText, type: 'error', duration: 25000, timer: true });
            }
        });
        add({ content: 'Personnage créé', type: 'success', duration: 25000, timer: true });
        useRouter().replace({ name: 'character-id-edit', params: { id: id } })
        if(leave) useRouter().push({ name: 'character-id', params: { id: id } });
    }
    else
    {
        //@ts-ignore
        await useRequestFetch()(`/api/character/${id}`, {
            method: 'post',
            body: data.value,
            onResponseError: (e) => {
                add({ title: 'Erreur d\'enregistrement', content: e.response.status === 401 ? "Vous n'êtes pas autorisé à effectué cette opération" : e.response.statusText, type: 'error', duration: 25000, timer: true });
            }
        });
        add({ content: 'Personnage enregistré', type: 'success', duration: 25000, timer: true });
        if(leave) useRouter().push({ name: 'character-id', params: { id: id } });
    }
}

useShortcuts({
    "Meta_S": () =>save(false),
})
</script>

<template>
    <Head>
        <Title>d[any] - Edition de {{ data.name || 'nouveau personnage' }}</Title>
    </Head>
    <div class="flex flex-1 max-w-full flex-col align-center">
        <StepperRoot class="flex flex-1 flex-col justify-start items-center px-8 w-full h-full overflow-y-hidden" v-model="step">
            <div class="flex w-full flex-row gap-4 items-center justify-between px-4 bg-light-0 dark:bg-dark-0 z-20">
                <div></div>
                <div class="flex w-full flex-row gap-4 items-center justify-center relative">
                    <StepperItem :step="0" class="group"><StepperTrigger class="px-2 py-1 border-b border-transparent hover:border-accent-blue group-data-[state=active]:text-accent-blue">Peuples</StepperTrigger></StepperItem>
                    <StepperItem :disabled="data.people === undefined" :step="1" class="group flex items-center"><Icon icon="radix-icons:chevron-right" class="w-6 h-6 group-data-[disabled]:text-light-50 dark:group-data-[disabled]:text-dark-50 group-data-[disabled]:hover:border-transparent me-4" /><StepperTrigger class="px-2 py-1 border-b border-transparent hover:border-accent-blue disabled:text-light-50 dark:disabled:text-dark-50 disabled:hover:border-transparent group-data-[state=active]:text-accent-blue">Niveaux</StepperTrigger></StepperItem>
                    <StepperItem :disabled="data.people === undefined" :step="2" class="group flex items-center"><Icon icon="radix-icons:chevron-right" class="w-6 h-6 group-data-[disabled]:text-light-50 dark:group-data-[disabled]:text-dark-50 group-data-[disabled]:hover:border-transparent me-4" /><StepperTrigger class="px-2 py-1 border-b border-transparent hover:border-accent-blue disabled:text-light-50 dark:disabled:text-dark-50 disabled:hover:border-transparent group-data-[state=active]:text-accent-blue">Entrainement</StepperTrigger></StepperItem>
                    <StepperItem :disabled="data.people === undefined" :step="3" class="group flex items-center"><Icon icon="radix-icons:chevron-right" class="w-6 h-6 group-data-[disabled]:text-light-50 dark:group-data-[disabled]:text-dark-50 group-data-[disabled]:hover:border-transparent me-4" /><StepperTrigger class="px-2 py-1 border-b border-transparent hover:border-accent-blue disabled:text-light-50 dark:disabled:text-dark-50 disabled:hover:border-transparent group-data-[state=active]:text-accent-blue">Compétences</StepperTrigger></StepperItem>
                    <StepperItem :disabled="data.people === undefined" :step="4" class="group flex items-center"><Icon icon="radix-icons:chevron-right" class="w-6 h-6 group-data-[disabled]:text-light-50 dark:group-data-[disabled]:text-dark-50 group-data-[disabled]:hover:border-transparent me-4" /><StepperTrigger class="px-2 py-1 border-b border-transparent hover:border-accent-blue disabled:text-light-50 dark:disabled:text-dark-50 disabled:hover:border-transparent group-data-[state=active]:text-accent-blue">Aspect</StepperTrigger></StepperItem>
                </div>
                <div>
                    <Tooltip class="max-w-96" side="bottom" align="end" :message="stepTexts[step]"><Icon icon="radix-icons:question-mark-circled" class="w-5 h-5" /></Tooltip>
                </div>
            </div>
            <div class="flex-1 outline-none max-w-full w-full overflow-y-auto" v-show="step === 0">
                <PeopleSelector v-model="builder" :config="config" @next="step = 1" />
            </div>
            <div class="flex-1 outline-none max-w-full w-full overflow-y-auto" v-show="step === 1">
                <LevelEditor v-model="builder" :config="config" @next="step = 2" />
            </div>
            <!-- <div class="flex-1 outline-none max-w-full w-full h-full max-h-full overflow-y-auto" v-show="step === 2">
                <TrainingEditor v-model="builder" :config="config" @next="step = 3" />
            </div>
            <div class="flex-1 outline-none max-w-full w-fulloverflow-y-auto" v-show="step === 3">
                <AbilityEditor v-model="builder" :config="config" @next="step = 4" />
            </div>
            <div class="flex-1 outline-none max-w-full w-full overflow-y-auto" v-show="step === 4">
                <AspectSelector v-model="builder" :config="config" @next="save(true)" />
            </div> -->
        </StepperRoot>
    </div>
</template>