<script>
    import {getContext} from "svelte";
    import {uniqBy, debounce} from "lodash";
    import {previewTitle} from "../Preview";
    import {getErrorMessage} from "./errorMessage";
    import {sortByField} from "../../edges/sortEdges";
    import ReferenceInlineButtons from "./ReferenceInlineButtons.svelte";
    import Sortable from "../../libs/Sortable.svelte";
    import RenderField from "../../content/RenderField.svelte";
    import Icon from "../../common/Icon.svelte";
    import Datalist from "./Datalist.svelte";
    import {insertEdges} from "./reference.js";

    const channel = getContext("channel");
    export let field;
    export let id;
    export let record;
    export let graph;

    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);
    }

    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>

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

<input
        type="search"
        {id}
        on:keyup={updateResults}
        class="form-control dropdown-toggle"
        class:is-invalid={errorMessage}
        bind:value={search}
        placeholder={"Search for "+field.label}
        data-bs-toggle="dropdown"
        autocomplete="off"
        readonly={field.readonly && !isCreateMode}
/>

<div class="dropdown-menu w-100">

    {#if searchOptions}
        {#each searchOptions as option (option.id)}
            <div
                    on:click={(e) => insert(e, option)}
                    on:keypress={(e) => insert(e, option)}
            >
            <span class="dropdown-item">
                {previewTitle(channel.schemas, option)}
            </span>
            </div>

        {:else}

            Start typing...
        {/each}
    {/if}
    {#if search }
        <div
                on:click={(e) => saveNew(e,search)}
                on:keypress={(e) => saveNew(e,search)}
        >
                <span class="dropdown-item">
                    Add "{search}"
                </span>
        </div>
    {/if}
</div>


{#if references.length > 0}
    <div class="d-flex">
        {#each references as record (record.id)}
            <span class="badge rounded-pill bg-light text-dark  fs-6 mt-3">
                <div class="d-flex align-items-center ">
                      {previewTitle(channel.schemas, record)}
                    <button
                            on:click|preventDefault={(e) => removeReference(e, record.id)}
                            type="button"
                            class="btn-close btn-sm  ms-1"
                            style="font-size:10px"
                            aria-label="Close"
                    />
                </div>
            </span>
        {/each}
    </div>
{/if}



