<script>
    import {createEventDispatcher, getContext} from "svelte";
    import {debounce} from "lodash";
    import {previewTitle} from "../../records/Preview";


    const channel = getContext("channel");
    const dispatch = createEventDispatcher();

    export let value = "";
    export let field;

    let search = ""
    $: searchOptions = []


    const updateResults = debounce((e) => {
        axios
            .get(channel.lucentUrl + "/records/suggestions", {
                params: {
                    schema: field.collections[0],
                    field: "search",
                    value: search,
                    ui: "search",
                },
            })
            .then((response) => {
                searchOptions = response.data;
            })
            .catch((error) => {
                searchOptions = [];
                console.log(error);
            });
    }, 500);

    function apply(e, newOption) {
        e.preventDefault();
        value = newOption.id
        dispatch("addFilter");
        value = ""

    }

</script>

<input
        type="search"
        on:keyup={updateResults}
        class="form-control dropdown-toggle"
        bind:value={search}
        placeholder={"Search for "+field.label}
        data-bs-toggle="dropdown"
        autocomplete="off"
/>

<div class="dropdown-menu w-100">

    {#if searchOptions}
        {#each searchOptions as option (option.id)}
            <div
                    on:click={(e) => apply(e, option)}
                    on:keypress={(e) => apply(e, option)}
            >
            <span class="dropdown-item">
                {previewTitle(channel.schemas, option)}
            </span>
            </div>

        {:else}

            Start typing...
        {/each}
    {/if}
</div>




