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

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

    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    $: errorMessage = getErrorMessage(validationErrors, field.name);

    export let id;
    let wrapperDiv;
    let pickerInput;
    let pickerInstance;
    let flatpickrOptions = {
        appendTo: wrapperDiv,
        static: true,
        allowInput: true,
        altInput: true,
        altFormat: "Y-m-d H:i:S",
        dateFormat: "Z",
        enableTime: true,
        time_24hr: true,
        enableSeconds: true,
    };

    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" bind:this={wrapperDiv}>

    <input
            type="text"
            {id}
            class="form-control"
            class:is-invalid={errorMessage}
            bind:value
            bind:this={pickerInput}
            autocomplete="off"
            readonly={field.readonly && !isCreateMode}
    />
    <span class="system-help-text"
    >Dates are displayed according to your timezone: {timezone}</span
    >

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