<template>
    <Head>
        <Title>d[any] - Configuration du projet</Title>
    </Head>
    <div class="flex flex-1 flex-row gap-4 p-6">
        <TreeRoot v-slot="{ flattenItems }" class="list-none select-none border border-light-35 dark:border-dark-35 text-light-100 dark:text-dark-100 p-2 xl:text-base text-sm overflow-auto w-[450px]" :items="navigation ?? undefined" :get-key="(item) => item.path" :defaultExpanded="flatten(navigation ?? [])">
            <TreeItem v-for="item in flattenItems" v-slot="{ handleToggle, handleSelect, isExpanded, isSelected }" :key="item._id" :style="{ 'padding-left': `${item.level - 0.5}em` }" v-bind="item.bind" class="flex items-center px-2 outline-none relative cursor-pointer hover:bg-light-20 dark:hover:bg-dark-20 data-[selected]:bg-light-35 dark:data-[selected]:bg-dark-35" @select.prevent @toggle.prevent>
                <span class="py-2 px-2" @click="handleToggle" v-if="item.hasChildren" >
                    <Icon :icon="isExpanded ? 'lucide:folder-open' : 'lucide:folder'"/>
                </span>
                <div class="ps-2 py-1 flex-1 truncate" :class="{'!ps-4 border-s border-light-35 dark:border-dark-35': !item.hasChildren}" :title="item.value.title" @click="() => { handleSelect();  selected = isSelected ? undefined : item.value; }">
                    {{ item.value.title }}
                </div>
            </TreeItem>
        </TreeRoot>
        <div v-if="selected" class="flex-1 flex justify-start items-start">
            <div class="flex flex-col flex-1 justify-start items-start">
                <input type="text" v-model="selected.title" placeholder="Titre" class="flex-1 mx-4 h-16 w-full caret-light-50 dark:caret-dark-50 text-light-100 dark:text-dark-100 placeholder:text-light-50 dark:placeholder:text-dark-50 appearance-none outline-none px-3 py-1 text-5xl font-thin bg-transparent" />
                <div class="flex ms-6 flex-col justify-start items-start">
                    <Tooltip message="Consultable uniquement par le propriétaire" side="right"><Switch label="Privé" v-model="selected.private" /></Tooltip>
                    <Tooltip message="Afficher dans le menu de navigation" side="right"><Switch label="Navigable" v-model="selected.navigable" /></Tooltip>
                </div>
            </div>
        </div>
    </div>
</template>


<script setup lang="ts">
import type { NavigationTreeItem } from '~/server/api/navigation.get';
import { Icon } from '@iconify/vue/dist/iconify.js';

definePageMeta({
    rights: ['admin', 'editor'],
})

const route = useRouter().currentRoute;
const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path);

const toaster = useToast();
const saveStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle');

const { data: navigation, status, error } = await useLazyFetch(`/api/navigation`);
const selected = ref<NavigationTreeItem>();


function flatten(arr: NavigationTreeItem[]): string[]
{
    return arr.flatMap(e => [e.path, ...flatten(e.children ?? [])]);
}
async function save(): Promise<void>
{
    saveStatus.value = 'pending';
    try {
        await $fetch(`/api/navigation`, {
            method: 'post',
            body: navigation.value,
        });
        saveStatus.value = 'success';

        toaster.clear('error');
        toaster.add({
            type: 'success', content: 'Contenu enregistré', timer: true, duration: 10000
        });

        useRouter().push({ name: 'explore-path', params: { path: path.value } });
    } catch(e: any) {
        toaster.add({
            type: 'error', content: e.message, timer: true, duration: 10000
        })
        saveStatus.value = 'error';
    }
}
</script>