<template>
	<Head>
		<Title>d[any] - Configuration du projet</Title>
	</Head>
	<div class="flex flex-1 flex-row gap-4 p-6 items-start">
		<DraggableTree 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] max-h-full" 
		:items="navigation ?? undefined" :get-key="(item) => item.path" @updateTree="drop">
			<template #default="{ handleToggle, handleSelect, isExpanded, isSelected, isDragging, isDraggedOver, item }">
				<div class="flex flex-1 px-2" :class="{ 'opacity-50': isDragging }" :style="{ 'padding-left': `${item.level - 0.5}em` }">
					<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>
				</div>
			</template>
			<template #hint="{ instruction }">
				<div v-if="instruction" class="absolute h-full w-full top-0 left-0 border-light-50 dark:border-dark-50" :class="{
					'!border-b-2': instruction?.type === 'reorder-below',
					'!border-t-2': instruction?.type === 'reorder-above',
					'!border-2 rounded': instruction?.type === 'make-child',
					}"></div>
			</template>
		</DraggableTree>
		<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';
import type { Instruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/dist/types/tree-item';
import { parsePath } from '#shared/general.utils';

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 } = await useLazyFetch(`/api/navigation`);
const selected = ref<NavigationTreeItem>();

const tree = {
  remove(data: NavigationTreeItem[], id: string): NavigationTreeItem[] {
	return data
	  .filter(item => parsePath(item.title) !== id)
	  .map((item) => {
		if (tree.hasChildren(item)) {
		  return {
			...item,
			children: tree.remove(item.children ?? [], id),
		  };
		}
		return item;
	  });
  },
  insertBefore(data: NavigationTreeItem[], targetId: string, newItem: NavigationTreeItem): NavigationTreeItem[] {
	return data.flatMap((item) => {
	  if (parsePath(item.title) === targetId)
		return [newItem, item];

	  if (tree.hasChildren(item)) {
		return {
		  ...item,
		  children: tree.insertBefore(item.children ?? [], targetId, newItem),
		};
	  }
	  return item;
	});
  },
  insertAfter(data: NavigationTreeItem[], targetId: string, newItem: NavigationTreeItem): NavigationTreeItem[] {
	return data.flatMap((item) => {
	  if (parsePath(item.title) === targetId)
		return [item, newItem];

	  if (tree.hasChildren(item)) {
		return {
		  ...item,
		  children: tree.insertAfter(item.children ?? [], targetId, newItem),
		};
	  }

	  return item;
	});
  },
  insertChild(data: NavigationTreeItem[], targetId: string, newItem: NavigationTreeItem): NavigationTreeItem[] {
	return data.flatMap((item) => {
	  if (parsePath(item.title) === targetId) {
		// already a parent: add as first child
		return {
		  ...item,
		  // opening item so you can see where item landed
		  isOpen: true,
		  children: [newItem, ...item.children ?? []],
		};
	  }

	  if (!tree.hasChildren(item))
		return item;

	  return {
		...item,
		children: tree.insertChild(item.children ?? [], targetId, newItem),
	  };
	});
  },
  find(data: NavigationTreeItem[], itemId: string): NavigationTreeItem | undefined {
	for (const item of data) {
	  if (parsePath(item.title) === itemId)
		return item;

	  if (tree.hasChildren(item)) {
		const result = tree.find(item.children ?? [], itemId);
		if (result)
		  return result;
	  }
	}
  },
  getPathToItem({
	current,
	targetId,
	parentIds = [],
  }: {
	current: NavigationTreeItem[]
	targetId: string
	parentIds?: string[]
  }): string[] | undefined {
	for (const item of current) {
	  if (parsePath(item.title) === targetId)
		return parentIds;

	  const nested = tree.getPathToItem({
		current: (item.children ?? []),
		targetId,
		parentIds: [...parentIds, parsePath(item.title)],
	  });
	  if (nested)
		return nested;
	}
  },
  hasChildren(item: NavigationTreeItem): boolean {
	return (item.children ?? []).length > 0;
  },
}

function updateTree(instruction: Instruction, itemId: string, targetId: string) {
	if(!navigation.value)
		return;

	const item = tree.find(navigation.value, itemId);

	if(!item)
		return;
	
	if (instruction.type === 'reparent') {
		const path = tree.getPathToItem({
			current: navigation.value,
			targetId: targetId,
		});
		if (!path) {
			console.error(`missing ${path}`);
			return;
		}

		const desiredId = path[instruction.desiredLevel];
		let result = tree.remove(navigation.value, itemId);
		result = tree.insertAfter(result, desiredId, item);
		return result;
	}

	// the rest of the actions require you to drop on something else
	if (itemId === targetId)
		return navigation.value;

	if (instruction.type === 'reorder-above') {
		let result = tree.remove(navigation.value, itemId);
		result = tree.insertBefore(result, targetId, item);
		return result;
	}

	if (instruction.type === 'reorder-below') {
		let result = tree.remove(navigation.value, itemId);
		result = tree.insertAfter(result, targetId, item);
		return result;
	}

	if (instruction.type === 'make-child') {
		let result = tree.remove(navigation.value, itemId);
		result = tree.insertChild(result, targetId, item);
		return result;
	}

  return navigation.value;
}

function drop(instruction: Instruction, itemId: string, targetId: string)
{          
	navigation.value = updateTree(instruction, itemId, targetId) ?? navigation.value;
}
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>