<script>
    import { post } from "../../../modules/remote";
    import { getApp } from "../../../app";
    import FieldLabel from "./FieldLabel.svelte";
    import FieldError from "./FieldError.svelte";
    let { channel, record, schemaField, dataField, locale, validationError } =
        $props();
    let originalValue = dataField?.value ?? schemaField.props.default;
    let newValue = $state(originalValue);
    let valuesChanged = $derived(newValue !== originalValue);
    // let validationErrorState = $state(validationError);
    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 {
                    validationError = data.validationError;
                    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="min-width: 400px;">
    <label>
        <FieldLabel {locale} {channel} {schemaField}></FieldLabel>

        <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={hasError ? "true" : ""} -->
        <FieldError {schemaField} {validationError}></FieldError>
    </label>
</div>
