<script lang="ts">
    import {Button, Dropdown, DropdownItem, Search} from 'flowbite-svelte'

    export let selected: string | null = null
    export let items: {name: string, value: string}[] = []

    export let searchValue = items.find(item => item.value === selected)?.name || ''
    let open = false

    $: filteredItems = items.filter(item => item.name.toLowerCase().includes(searchValue.toLowerCase())).filter((value, index) => index < 5)

    function selectItem(item: {name: string, value: string}) {
        selected = item.value
        searchValue = ""
        open = false
    }
</script>

<Button color="alternative" on:click={() => open = true}>{selected === null ? 'Auswählen' : items.find(value => value.value === selected)?.name}</Button>
<Dropdown bind:open class="w-60">
    <div class="overflow-y-auto p-3 text-sm w-60" slot="header">
        <Search bind:value={searchValue} on:focus={() => open = true} on:keydown={() => open = true}/>
    </div>
    {#each filteredItems as item}
        <button on:click={() => selectItem(item)} class="rounded p-2 hover:bg-gray-100 dark:hover:bg-gray-600 w-full cursor-pointer border-b border-b-gray-600">
            {item.name}
        </button>
    {/each}
</Dropdown>
