import type { Accessor, Component } from 'solid-js'
import { createEffect, createMemo, For } from 'solid-js'
import { useBlk } from '../../data/VMs/BlockVM'
import { useRoots } from '../../ui/reactive'

export const FilteredBlockSelector: Component<{ filterString: Accessor<string>, onSelectionChanged: (evt: Event) => void }> = (props) => {
	// TODO implement via elix https://component.kitchen/elix/FilterComboBox
	const allRoots = useRoots()
	DEBUG('[FilteredBlockSelector]', { allRoots })
	const unfilteredMap = createMemo(() =>
		allRoots.map((rootID) => {
			const block = useBlk(rootID)
			const contentPlaintext = block.contentPlaintext
			return { rootID, contentPlaintext }
		}),
	)
	let filteredOptions = createMemo(() =>
		unfilteredMap().filter(({ rootID, contentPlaintext }) => contentPlaintext?.includes(props.filterString())),
	)
	DEBUG('[FilteredBlockSelector]', { unfiltered: filteredOptions })

	createEffect(() => {
		filteredOptions = filteredOptions
		DEBUG('[FilteredBlockSelector]', { filteredOptions })
	})
	return (
		<sl-select
			class='min-w-xs'
			placeholder='Search for a block to use as your home block'
			clearable
			open={true}
			onsl-input={props.onSelectionChanged}
			placement='bottom'
		>
			<div w-8 h-8 slot='prefix' class='i-ph:dot-duotone scale-115' />
			<For each={filteredOptions()}>
				{({ rootID, contentPlaintext }) => <sl-option value={rootID}>{contentPlaintext}</sl-option>}
			</For>
		</sl-select>
	)
}
