<script>
    import Icon from "../../common/Icon.svelte";
    import {createEventDispatcher} from "svelte";
    import FilterReferenceInput from "./FilterReferenceInput.svelte";
    import Dropdown from "../../common/Dropdown.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);
    }

    let filterableFields = [...schema.fields, ...systemFieldsFiltered].filter(
        (f) => !["file", "json"].includes(f.info?.name ?? f.ui)
    );
    let selectedField;

    let selectedInput = "";
    $: operatorsFiltered = operators.filter(
        (o) => o.uis.includes(selectedField?.info?.name) || o.uis[0] == "*"
    );

    $: selectedOperator = operatorsFiltered[0];

    function addFilter(e) {
        e.preventDefault();
        let filterPrefix = "";
        let filterKey;
        if (schema.fields.find(f => f.name === selectedField.name)) {

            if (selectedField.info.name == "reference" && selectedOperator.name == "eq") {
                filterPrefix = "children." + selectedField.name + ".id";
                filterKey = `filter[${filterPrefix}]`;
            } else {
                filterPrefix = "data.";
                filterKey = `filter[${filterPrefix + selectedField.name}_${selectedOperator.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.hide()
        } else {
            window.location = url;
        }
    }

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

<div class="mx-2 d-flex align-items-center">
        <Dropdown bind:this={dropdown} width="300">
            <div slot="button">
                <Icon icon="filter"/>
                <span class="ms-1">Filter</span>
            </div>

            <div class="px-3 py-1 d-flex align-items-center">
                <select bind:value={selectedField} class="form-select">
                    {#each filterableFields as field}
                        <option value={field}>{field.label}</option>
                    {/each}
                </select>
            </div>
            <div class="px-3 py-1 d-flex align-items-center">
                <select class="form-select" bind:value={selectedOperator}>
                    {#each operatorsFiltered as operator}
                        <option value={operator}>{operator.label}</option>
                    {/each}
                </select>
            </div>
            <div class="px-3 py-1 d-flex align-items-center">
                {#if selectedField?.info?.name === "reference" && selectedOperator.name === "eq"}
                    <FilterReferenceInput field={selectedField} bind:value={selectedInput} on:addFilter={addFilter}/>
                {:else}
                    <input
                            type="text"
                            class="form-control"
                            bind:value={selectedInput}
                    />
                {/if}
            </div>
            <div class="px-3 py-1 d-flex align-items-center">
                <button
                        on:click={addFilter}
                        class="btn btn-outline-primary"
                        type="button"
                >
                    Add filter
                </button>
            </div>

            <hr/>
            <div><h6 class="dropdown-header">Advanced filters</h6></div>
            <form on:submit={submitSearch}>
                <div class="px-3 py-1 d-flex align-items-center">
                    <input
                            bind:value={search}
                            type="search"
                            class="form-control"
                            placeholder="Advanced filters"
                            required
                    />
                </div>
            </form>
        </Dropdown>
</div>
