<script lang="ts">
	import { TFolder, type App } from "obsidian";
	import TextInputSuggest, { type Item } from "./TextInputSuggest.svelte";
	import type { StringKeys } from "@utils/types";

	type Props = {
		app: App;
		id: string;
		asString?: boolean;
		property?: StringKeys<TFolder>;
		inFolder?: string;
		value?: TFolder | string;
		disabled?: boolean;
		onSelected?: (folderOrPath: TFolder | string) => void;
	};

	let {
		app,
		id,
		asString,
		property = "path",
		inFolder,
		value = $bindable(),
		disabled,
		onSelected,
	}: Props = $props();

	let items: Item<TFolder | string>[] = $state([]);

	function handleChange(query: string) {
		items = app.vault
			.getAllFolders()
			.filter(
				(f) =>
					(inFolder === undefined || f.path.startsWith(inFolder)) &&
					f[property].toLowerCase().includes(query.toLowerCase()),
			)
			.map((f) => ({
				text: f[property],
				value: asString ? f[property] : f,
			}));
	}
</script>

<TextInputSuggest
	{id}
	{items}
	bind:value
	{disabled}
	onChange={handleChange}
	{onSelected}
/>
