<!--
  -   This file is a part of the SteamWar software.
  -
  -   Copyright (C) 2023 SteamWar.de-Serverteam
  -
  -   This program is free software: you can redistribute it and/or modify
  -   it under the terms of the GNU Affero General Public License as published by
  -   the Free Software Foundation, either version 3 of the License, or
  -   (at your option) any later version.
  -
  -   This program is distributed in the hope that it will be useful,
  -   but WITHOUT ANY WARRANTY; without even the implied warranty of
  -   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  -   GNU Affero General Public License for more details.
  -
  -   You should have received a copy of the GNU Affero General Public License
  -   along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

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


  interface Props {
    selected?: string | null;
    items?: { name: string, value: string }[];
    maxItems?: number;
    leftText?: boolean;
    searchValue?: any;
  }

  let {
    selected = $bindable(null),
    items = [],
    maxItems = 5,
    leftText = false,
    searchValue = $bindable(items.find(item => item.value === selected)?.name || "")
  }: Props = $props();

    let filteredItems = $derived(items.filter(item => item.name.toLowerCase().includes(searchValue.toLowerCase())).filter((value, index) => index < maxItems));

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

<Button color="light">{selected === null ? 'Auswählen' : items.find(value => value.value === selected)?.name}</Button>
<Dropdown class="w-60">
    {#snippet header()}
        <div class="overflow-y-auto p-3 text-sm w-60" >
            <Search bind:value={searchValue} />
        </div>
    {/snippet}
    {#each filteredItems as item (item)}
        <button onclick={() => 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"
                class:text-left={leftText}>
            {item.name}
        </button>
    {/each}
</Dropdown>
