<script>
    import Datalist from "./Datalist.svelte";
    import {getErrorMessage} from "./errorMessage";

    export let field;
    export let value;
    export let isCreateMode;
    export let validationErrors;

    $: errorMessage = getErrorMessage(validationErrors, field.name);
    $: search = "";
    export let id;
    let list;

    $: listMode = field.optionsFrom && !(field.readonly && !isCreateMode);
</script>

<div class="mb-0">
    {#if listMode}
        <div class="dropdown">
            <input
                type="search"
                {id}
                on:keyup={list.update}
                on:focus={list.update}
                class="form-control dropdown-toggle"
                class:is-invalid={errorMessage}
                bind:value={search}
                placeholder="Search for options"
                data-bs-toggle="dropdown"
                autocomplete="off"
                aria-expanded="false"
                readonly={field.readonly && !isCreateMode}
            />

            <div class="dropdown-menu w-100">
                {#if field.optionsFrom}
                    <Datalist
                        {field}
                        bind:this={list}
                        bind:value
                        bind:search
                    />
                {/if}
            </div>
        </div>
        {#if value}
            <span class="badge rounded-pill bg-light text-dark  fs-6 mt-3">
                <div class="d-flex align-items-center ">
                    {value}
                    <button
                        on:click|preventDefault={(e) => (value = "")}
                        type="button"
                        class="btn-close btn-sm  ms-1"
                        style="font-size:10px"
                        aria-label="Close"
                    />
                </div>
            </span>
        {/if}
    {:else}
        <input
            type="text"
            {id}
            class="form-control"
            class:is-invalid={errorMessage}
            bind:value
            autocomplete="off"
            readonly={field.readonly && !isCreateMode}
        />
    {/if}

    {#if errorMessage}
        <div class="invalid-feedback d-block">
            {errorMessage}
        </div>
    {/if}
</div>
