<script>
    import { get, post } from "../../../modules/remote";
    import { getApp } from "../../../app";
    import { getLocaleName } from "../locale.svelte.js";
    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 errorMessage = $state("");
    // let validationErrorState = $state(validationError);
    let hasError = $derived(!!validationError);
    const app = getApp();

    let suggestionsLoaded = $state(false);
    let suggestions = $state([]);

    function handleAddRecord(e) {
        // Add logic to handle adding a record
        if (suggestionsLoaded) {
            return;
        }
        get(
            app.url("records/suggest"),
            { schemas: schemaField.props.schemas },
            (data, err) => {
                suggestionsLoaded = true;
                suggestions = data;
            },
        );
    }

    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;
                }
            },
        );
    }
</script>

<div style="min-width: 400px;">
    <label>
        {#if locale !== "main"}
            {getLocaleName(channel, locale)} >
        {/if}
        {schemaField.name} <br />
        <details class="dropdown">
            <summary onclick={handleAddRecord}>Add Record</summary>
            {#if suggestionsLoaded}
                <ul>
                    {#each suggestions as suggestion}
                        <li><a href="#">{suggestion.title}</a></li>
                    {/each}
                    <li><a href="#">More</a></li>
                </ul>
            {:else}
                <progress />
            {/if}
        </details>

        {#if hasError}
            <small id={schemaField.id + "-help"}
                >{validationError.message}</small
            >
        {:else if schemaField.help != ""}
            <small id={schemaField.id + "-help"}>{schemaField.help}</small>
        {/if}
    </label>
</div>
