<script>
    import {getContext} from "svelte";
    import {debounce} from "lodash";
    import {previewTitle} from "../Preview";
    import {getErrorMessage} from "./errorMessage";
    import {insertEdges} from "./reference.js";
    import Icon from "../../common/Icon.svelte";

    const channel = getContext("channel");
    export let field;
    export let id;
    export let record;
    export let graph;
    let searchEl;
    export let validationErrors;
    $: errorMessage = getErrorMessage(validationErrors, field.name);

    $: references = graph.edges
        .filter((edge) => edge.field === field.name)
        .map((edge) => {
            return graph.records.find((increc) => increc.id == edge.target && record.id == edge.source);
        }).filter((rec) => (rec?.id ? true : false)) ?? [];

    let search = ""
    $: searchOptions = []


    function removeReference(e, recordId) {
        e.preventDefault();
        graph.edges = graph.edges.filter(
            (edge) => !(edge.target === recordId && edge.field === field.name)
        );
    }

    function saveNew(e, newValue) {
        e.preventDefault();
        axios
            .post(channel.lucentUrl + "/records", {
                isCreateMode: true,
                record: {
                    schema: field.collections[0],
                    status: "published",
                    data: {
                        [field.searchField]: newValue
                    }
                },
            })
            .then((response) => {
                searchOptions = [];
                insert(e, response.data.records[0]);
                console.log(response)
            })
            .catch((error) => {
                searchOptions = [];
                console.log(error);
            });
    }

    function insert(e, insertRecord) {
        e.preventDefault();
        graph = insertEdges(graph, record, [insertRecord], field.name, e.detail.action);
        search = ""
        searchEl.focus()
        searchEl.blur()
    }

    const updateResults = debounce((e) => {
        axios
            .get(channel.lucentUrl + "/records/suggestions", {
                params: {
                    schema: field.collections[0],
                    field: field.searchField,
                    value: search,
                    ui: "text",
                },
            })
            .then((response) => {
                searchOptions = response.data;
            })
            .catch((error) => {
                searchOptions = [];
                console.log(error);
            });
    }, 500);


</script>
<div class="reference-tags">
    {#if errorMessage}
        <div class="invalid-feedback d-block mb-3">
            {errorMessage}
        </div>
    {/if}

    <input
            type="search"
            bind:this={searchEl}
            {id}
            on:keyup={updateResults}
            class:is-invalid={errorMessage}
            bind:value={search}
            placeholder={"Search for "+field.label}
            autocomplete="off"
    />

    <div class="reference-tags-results">

        {#if searchOptions}
            {#each searchOptions as option (option.id)}
                <div
                        class="reference-tags-option"
                        role="button"
                        tabindex="0"
                        on:click={(e) => insert(e, option)}
                        on:keypress={(e) => insert(e, option)}
                >
                    {previewTitle(channel.schemas, option)}
                </div>

            {:else}
                <div
                        class="start-typing">
                    Start typing...
                </div>
            {/each}
        {/if}
        {#if search }
            <div
                    class="reference-tags-option"
                    role="button"
                    tabindex="0"
                    on:click={(e) => saveNew(e,search)}
                    on:keypress={(e) => saveNew(e,search)}
            >
                Add "{search}"
            </div>
        {/if}
    </div>
</div>

{#if references.length > 0}
    <div style="display: flex;align-items: center;gap: 4px">
        {#each references as record (record.id)}
            <span class="reference-tags-selected-value">
                 <a
                         class="record-title"
                         href="{channel.lucentUrl}/records/{record.id}"
                 >
                      {previewTitle(channel.schemas, record)}
                    </a>

                <button
                        on:click|preventDefault={(e) => removeReference(e, record.id)}
                        type="button"
                        class="button-text"
                        aria-label="Close"
                >
            <Icon width={12} height={12} icon="close"></Icon>
        </button>

            </span>
        {/each}
    </div>
{/if}



