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

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

    let list;

    function fixDecimals(e) {
        const number = e.currentTarget.value;
        const formattedNumber = formatNumber(number);
        value = isNaN(formattedNumber) ? null : formattedNumber;
    }

    function formatNumber(number) {
        return parseFloat(number).toFixed(field.decimals);
    }

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

<div class="mb-0">

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

            <ul class="dropdown-menu w-100">
                {#if field.optionsFrom}
                    <Datalist
                        {field}
                        bind:this={list}
                        {schemas}
                        bind:value
                        bind:search
                    />
                {/if}
            </ul>
        </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="number"
            {id}
            class="form-control"
            class:is-invalid={errorMessage}
            on:change={fixDecimals}
            bind:value
            autocomplete="off"
            readonly={field.readonly && !isCreateMode}
        />
    {/if}

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