<script>
    import { post } from "../../../modules/remote";
    import { getApp } from "../../../app";
    import { getLocaleName } from "../locale.svelte.js";
    let { channel, record, schemaField, dataField, locale, errors } = $props();
    let originalValue = dataField?.value ?? schemaField.props.default;
    let newValue = $state(originalValue);
    let valuesChanged = $derived(newValue !== originalValue);
    let errorMessage = $state("");
    let validationErrors = $state(errors);
    let hasErrors = $derived(validationErrors.length > 0);
    const app = getApp();

    function save() {
        if (!valuesChanged) {
            return;
        }

        post(
            app.url("records/fields"),
            {
                recordId: record.id,
                id: schemaField.id,
                locale: locale,
                value: newValue,
            },
            (data, err) => {
                if (err.isNotEmpty()) {
                    errorMessage = err.first();
                } else {
                    validationErrors = data.validationErrors;
                    originalValue = newValue;
                }
            },
        );
    }
    let delayMs = 1000;
    let timer = $state(undefined);
    let isComposing = $state(false);

    const schedule = () => {
        if (isComposing) {
            return;
        }
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(flush, delayMs);
    };

    const flush = () => {
        if (timer) {
            clearTimeout(timer);
            timer = undefined;
        }
        // value = inputValue;
        save();
    };

    const handleInput = () => {
        schedule();
    };

    const handleKeydown = (event) => {
        if (event.key === "Enter") {
            flush();
        }
    };

    const handleBlur = () => {
        flush();
    };

    const handleCompositionStart = () => {
        isComposing = true;
    };

    const handleCompositionEnd = () => {
        isComposing = false;
    };
</script>

<!-- <div style="position: relative;">
    {#if field.selectOptions}
        <Autocomplete {field} bind:value></Autocomplete>
    {: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> -->
<div style="min-width: 400px;">
    <label>
        {#if locale !== "main"}
            {getLocaleName(channel, locale)} >
        {/if}
        {schemaField.name} <br />

        <input
            type="text"
            bind:value={newValue}
            autocomplete="off"
            readonly={schemaField.readonly}
            aria-describedby={schemaField.id + "-help"}
            oninput={handleInput}
            onkeydown={handleKeydown}
            onblur={handleBlur}
            oncompositionstart={handleCompositionStart}
            oncompositionend={handleCompositionEnd}
            aria-invalid={hasErrors ? "true" : ""}
        />
        {#if hasErrors}
            <small id={schemaField.id + "-help"}
                >{validationErrors[0].message}</small
            >
        {:else if schemaField.help != ""}
            <small id={schemaField.id + "-help"}>{schemaField.help}</small>
        {/if}
    </label>
</div>
