<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 isCreateMode;
    export let validationErrors;
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    $: errorMessage = getErrorMessage(validationErrors, field.name);

    export let id;
    let pickerInput;
    let pickerInstance;
    let flatpickrOptions = {
        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">

    <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>
