<script>
    import Icon from "../../common/Icon.svelte";
    import {createEventDispatcher} from "svelte";
    import Dropdown from "../../common/Dropdown.svelte";
    import FilterReferenceInput from "./FilterReferenceInput.svelte";

    const dispatch = createEventDispatcher();
    export let schema;
    export let systemFields = [];
    export let operators;
    export let inModal;
    export let modalUrl;

    let dropdown;
    let search = "";
    let systemFieldsFiltered = systemFields;
    if (schema.type === "collection") {
        systemFieldsFiltered = systemFields.filter((f) => f.files === false);
    }

    function submitSearch(e) {
        e.preventDefault();
        let filterKeyValue = search.split("=")[0] ?? "";
        if (!filterKeyValue) {
            return;
        }
        let filterKey = `filter[${filterKeyValue}]`;
        let filterValue = search.split("=")[1] ?? "";

        if (!filterValue) {
            return;
        }

        const url = new URL(modalUrl ?? window.location.href);
        url.searchParams.set("skip", "0");
        url.searchParams.set(filterKey, filterValue);
        if (inModal) {
            dispatch("refresh", url);
        } else {
            window.location.replace(url);
        }
        resetFilters();
    }


    //     New Start
    let selectedInput = null;
    let activeField = null;
    let activeReference = null;
    let activeOperator = null;
    let activeMenu = "main";
    let activeOperators = null;
    let dataFields = [...schema.fields, ...systemFieldsFiltered].filter(
        (f) => !["file", "json", "reference"].includes(f.info?.name ?? f.ui)
    );
    let referenceFields = [...schema.fields].filter(
        (f) => ["reference"].includes(f.info?.name ?? f.ui)
    );

    function selectField(e, field) {
        activeField = field;
        activeOperators = operators.filter(
            (o) => o.uis.includes(activeField?.info?.name) || o.uis[0] === "*"
        );
    }

    function selectReference(e, field) {
        activeReference = field;
        activeOperator = operators.find(o => o.name === "eq")
    }

    function selectOperator(e, operator) {
        activeOperator = operator;
        if (!operator.hasValue) {
            applyFilter(e)
        }
    }

    function applyFilter(e) {
        e.preventDefault();
        let filterPrefix = "";
        let filterKey;
        let selectedField = activeField ?? activeReference;
        if (schema.fields.find(f => f.name === selectedField.name)) {
            if (selectedField.info.name === "reference" && activeOperator.name === "eq") {
                filterPrefix = "children." + selectedField.name + ".id";
                filterKey = `filter[${filterPrefix}]`;
            } else {
                filterPrefix = "data.";
                filterKey = `filter[${filterPrefix + selectedField.name}_${activeOperator.name}]`;
            }

        }

        const url = new URL(modalUrl ?? window.location.href);
        url.searchParams.set("skip", "0");
        url.searchParams.set(filterKey, selectedInput);
        if (inModal) {
            dispatch("refresh", url);
            dropdown.close()
        } else {
            window.location.href = url.toString();
        }
        resetFilters();
    }

    function resetFilters() {
        activeField = null;
        activeOperator = null;
        activeMenu = "main";
        activeReference = null;
    }

</script>


<div>
    <Dropdown bind:this={dropdown}>
        <div slot="button">
            <Icon icon="filter"/>
            <span class="ms-1">Filter</span>
        </div>
        <div class:hide={activeMenu !== "main"}>
            <button class="dropdown-item button" on:click={e => activeMenu = "byField" }>
                Filter by field
            </button>
            <button class="dropdown-item button" on:click={e => activeMenu = "byReference" }>
                Filter by Reference
            </button>
            <button class="dropdown-item button" on:click={e => activeMenu = "advanced" }>
                Advanced filter
            </button>
        </div>
        <div class:hide={activeMenu !== "byField"}>
            {#if !activeField}
                <button class="dropdown-item button" on:click={e =>   activeMenu = "main"  }>
                    <Icon icon="arrow-left"></Icon>
                    Back
                </button>
                {#each dataFields as field}
                    <button class="dropdown-item button" on:click={e => selectField(e,field)}>
                        {field.label}
                    </button>
                {/each}
            {/if}

            {#if activeField && !activeOperator}
                <button class="dropdown-item button" on:click={e =>   activeField = null  }>
                    <Icon icon="arrow-left"></Icon>
                    Back
                </button>
                <div class="selected-filter">field: {activeField.label}</div>

                {#each activeOperators as operator}
                    <button class="dropdown-item button" on:click={e => selectOperator(e,operator)}>
                        {operator.label}
                    </button>
                {/each}
            {/if}
            {#if activeField && activeOperator}
                <button class="dropdown-item button" on:click={e =>   activeOperator = null  }>
                    <Icon icon="arrow-left"></Icon>
                    Back
                </button>
                <div class="selected-filter">field: {activeField.label} operator: {activeOperator.label}</div>
                <div class="filter-input">
                    <input
                            type="text"
                            class="form-control"
                            bind:value={selectedInput}
                    />
                </div>
                <button
                        on:click={applyFilter}
                        class="button applied-filter"
                        type="button"
                >
                    Add filter
                </button>
            {/if}

        </div>
        <div class:hide={activeMenu !== "byReference"}>
            {#if !activeReference}
                <button class="dropdown-item button" on:click={e =>   activeMenu = "main"  }>
                    <Icon icon="arrow-left"></Icon>
                    Back
                </button>
                {#each referenceFields as field}
                    <button class="dropdown-item button" on:click={e => selectReference(e,field)}>
                        {field.label}
                    </button>
                {/each}
            {/if}
            {#if activeReference}
                <button class="dropdown-item button" on:click={e =>   activeReference = null  }>
                    <Icon icon="arrow-left"></Icon>
                    Back
                </button>
                <div class="selected-filter">field: {activeReference.label}</div>
                <div class="mt-2">
                    <FilterReferenceInput field={activeReference} bind:value={selectedInput}
                                          on:addFilter={applyFilter}/>
                </div>
            {/if}


        </div>
        <div class:hide={activeMenu !== "advanced"}>
            <button class="dropdown-item button" on:click={e =>   activeMenu = "main"  }>
                <Icon icon="arrow-left"></Icon>
                Back
            </button>
            <form on:submit={submitSearch}>
                <input
                        bind:value={search}
                        type="search"
                        class="mb-2 mt-2"
                        placeholder="Advanced filters"
                        required
                />

                <button class="button applied-filter">
                    Submit
                </button>

            </form>


        </div>
    </Dropdown>

</div>
