<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>
<div class="reference-tags">
    <input
            type="search"
            on:keyup={updateResults}
            bind:value={search}
            placeholder={"Search for "+field.label}
            autocomplete="off"
    />

    <div class="reference-tags-results">

        {#if searchOptions}
            {#each searchOptions as option (option.id)}
                <div
                        class="reference-tags-option"
                        role="button"
                        tabindex="0"
                        on:click={(e) => apply(e, option)}
                        on:keypress={(e) => apply(e, option)}
                >
                    {previewTitle(channel.schemas, option)}
                </div>

            {:else}
                <div
                        class="start-typing">
                    Start typing...
                </div>
            {/each}
        {/if}
    </div>
</div>




