<script>
    import {onMount} from "svelte";
    import flatpickr from "flatpickr";
    import "flatpickr/dist/flatpickr.css";
    import "flatpickr/dist/themes/light.css";
    import {getErrorMessage} from "./errorMessage";

    export let field;
    export let value;
    export let id;
    export let isCreateMode;
    export let validationErrors;
    $: errorMessage = getErrorMessage(validationErrors, field.name);
    let pickerInput;
    let pickerInstance;
    let flatpickrOptions = {
        enableTime: false,
        allowInput: true,
        dateFormat: "Y-m-d",
    };

    if (field.min) {
        flatpickrOptions.minDate = field.min;
    }

    if (field.max) {
        flatpickrOptions.maxDate = field.max;
    }

    onMount(() => {
        if (!field.readonly || isCreateMode) {

            pickerInstance = flatpickr(pickerInput, flatpickrOptions);
        }
    });
</script>

<div class="mb-0">


    <input
            type="text"
            {id}
            class="form-control"
            class:is-invalid={errorMessage}
            bind:value
            bind:this={pickerInput}
            autocomplete="off"
            readonly={field.readonly && !isCreateMode}
    />

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