<script>
    import { get, post } from "../../../modules/remote";
    import { getApp } from "../../../app";
    import { getLocaleName } from "../locale.svelte.js";
    let {
        channel,
        record,
        schemaField,
        dataField,
        locale,
        validationError,
        edgeRecordPreviews,
    } = $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([]);
    let selectedRecordIds = $state([]);
    let dialog = $state();

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

    function handleModalClose(e) {
        dialog.close();
    }

    function handleInsertSelected() {
        suggestionsLoaded = false;
        post(
            app.url("edges/many"),
            {
                toIds: selectedRecordIds,
                from: record.id,
                fieldId: schemaField.id,
                locale: locale,
            },
            (data, err) => {
                suggestionsLoaded = true;
                dialog.close();
                edgeRecordPreviews = [...edgeRecordPreviews, ...data];
            },
        );
    }
</script>

<div style="min-width: 400px;">
    <label>
        {#if locale !== "main"}
            {getLocaleName(channel, locale)} >
        {/if}
        {schemaField.name} <br />
    </label>
    {#if hasError}
        <small id={schemaField.id + "-help"}>{validationError.message}</small>
    {:else if schemaField.help != ""}
        <small id={schemaField.id + "-help"}>{schemaField.help}</small>
    {/if}

    <button onclick={handleModalOpen}>Choose record</button>

    <dialog bind:this={dialog}>
        <article>
            <header>
                <button onclick={handleModalClose} aria-label="Close" rel="prev"
                ></button>
                <p>
                    <strong>Records</strong>
                </p>
            </header>
            {#if suggestionsLoaded}
                <form>
                    <button onclick={handleInsertSelected}>
                        Insert selected
                    </button>
                    <table>
                        <tbody>
                            {#each suggestions as suggestion}
                                <tr>
                                    <td>
                                        <input
                                            type="checkbox"
                                            value={suggestion.id}
                                            bind:group={selectedRecordIds}
                                        />
                                    </td>
                                    <td>
                                        <a href="#">{suggestion.title}</a>
                                    </td>
                                    <td>
                                        <a href="#">
                                            {suggestion.schemaName}
                                        </a>
                                    </td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </form>
            {:else}
                <progress />
            {/if}
        </article>
    </dialog>
    <div>
        {#if edgeRecordPreviews.length == 0}
            No relations exist
        {:else}
            {#each edgeRecordPreviews as edgeRecordPreview}
                <div>
                    <a href="#">{edgeRecordPreview.recordPreview.title}</a>
                    {edgeRecordPreview.recordPreview.schemaName}
                </div>
            {/each}
        {/if}
    </div>
</div>
