<script lang="ts">
	import type { TFile } from "obsidian";
	import TextInputSuggest, { type Item } from "./TextInputSuggest.svelte";
	import type { StringKeys } from "@utils/types";
	import { getAppContext } from "@ui/stores/app";
	import { isInAnyFolder } from "@utils/fs";

	type Props = {
		id: string;
		property?: StringKeys<TFile>;
		folderFilter?: string[];
		value?: string;
		disabled?: boolean;
		onSelected?: (propertyValue: string) => void;
	};

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

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

	function handleChange(query: string) {
		items = app.vault
			.getMarkdownFiles()
			.filter(
				(f) =>
					(folderFilter === undefined ||
						isInAnyFolder(f, folderFilter)) &&
					f[property].toLowerCase().includes(query.toLowerCase()),
			)
			.map((f) => f[property]);
	}
</script>

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