<script>
    import {getContext} from "svelte";
    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 {insertEdges} from "./reference.js";

    const channel = getContext("channel");
    export let field;
    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 collections = channel.schemas.filter((aschema) =>
        field.collections.includes(aschema.name)
    );

    let collection = channel.schemas.filter((aschema) =>
        field.collections.includes(aschema.name)
    )[0];

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

    function sendToTop(e, recordId) {
        e.preventDefault();
        let ref = graph.edges.find(
            (edge) => edge.source === record.id && edge.target === recordId && edge.field === field.name
        );
        removeReference(e, recordId);
        graph.edges = [ref, ...graph.edges];
    }

    function sendToBottom(e, recordId) {
        e.preventDefault();
        let ref = graph.edges.find(
            (edge) => edge.source === record.id && edge.target === recordId && edge.field === field.name
        );
        removeReference(e, recordId);
        graph.edges = [...graph.edges, ref];
    }


    function reorder(e) {
        graph.edges = sortByField(e.detail.source, e.detail.target, graph.edges, field.name);
    }


    function insert(e) {
        e.preventDefault();
        graph = insertEdges(graph, record, e.detail.records, field.name, e.detail.action);
    }

    $:visibleColumns = [];
    // $: visibleColumns = collection.fields
    //     .filter((f) => f.ui !== "tab" && !f.trashed)
    //     .filter((f) => {
    //         return collection.visible.includes(f.name);
    //     });
</script>

{#if errorMessage}
    <div class="invalid-feedback d-block mb-3">
        {errorMessage}
    </div>
{/if}
<div class="inline-card-wrapper">
    <ReferenceInlineButtons
            buttonClass="mt-2"
            recordId={null}
            schemas={collections}
            on:insert={insert}
            on:save={insert}
    />
</div>
{#if references.length > 0}
    <div class="lx-table rounded">
        <table class="">
            <thead class="table-light">
            <tr>
                <th/>

                {#each visibleColumns as field}
                    <th
                            class="field-ui-{field.ui}"
                            scope="col"
                            title={field.help}
                            data-bs-toggle="tooltip"
                            data-bs-placement="top">{field.label}</th
                    >
                {/each}
                <th/>
            </tr>
            </thead>
            <Sortable isTable={true} on:update={reorder}>
                {#each references as record,index (record.id)}
                    <tr>
                        <td class="">
                            <div class="">
                                <div class="d-flex align-items-center">
                                    <a
                                            class="me-2 text-decoration-none text-dark fs-6"
                                            href="{channel.lucentUrl}/records/{record.id}"
                                            target="_blank"
                                    >
                                        {previewTitle(channel.schemas, record)}
                                    </a>
                                </div>
                            </div>
                        </td>
                        {#each visibleColumns as field, index}
                            <td class="field-ui-{field.ui}">
                                <RenderField
                                        {record}
                                        {graph}
                                        schema={collection}
                                        {field}
                                />
                            </td>
                        {/each}
                        <td>
                            <button
                                    class="trash-button  text-dark btn btn-sm btn-link"
                                    on:click={(e) =>
                                    removeReference(e, record.id)}
                            >
                                <Icon icon="trash-can"/>
                            </button>
                            {#if references.length > 30 && index > 0}
                                <button
                                        title="Send item to top"
                                        class="to-top-button  text-dark btn btn-sm btn-link"
                                        on:click={(e) =>
                                    sendToTop(e, record.id)}
                                >
                                    <Icon icon="circle-chevron-up"/>
                                </button>
                            {/if}
                            {#if references.length > 30 && index + 1 < references.length}
                                <button
                                        title="Send item to bottom"
                                        class="to-top-button  text-dark btn btn-sm btn-link"
                                        on:click={(e) =>
                                    sendToBottom(e, record.id)}
                                >
                                    <Icon icon="circle-chevron-down"/>
                                </button>
                            {/if}
                        </td>
                    </tr>
                {/each}
            </Sortable>
        </table>
    </div>
{/if}
