document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll("[name='redis-cache-delete']").forEach(button => {
        button.addEventListener("click", function (event) {
            event.preventDefault();

            let button = this;
            let cache = this.getAttribute("data-cache");

            if (button.disabled === true) {
                return;
            }

            button.disabled = true;
            button.textContent = "Deleting...";

            fetch(ajaxurl, {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: `action=rdg_blocks_delete_cache&cache=${cache}`,
            })
            .then((response) => response.text())
            .then((result) => {
                let item = this.parentElement.parentElement;

                button.disabled = false;
                button.textContent = "Delete";

                if (result == 'success') {
                    item.remove();
                } else {
                    let idSelector = `api_response_item_${cache}`.replace(/:/g, "\\:");
                    document.querySelector('.' + idSelector + ' pre').innerHTML = result;
                }
            })
            .catch((err) => console.error(err));
        });
    });

    document.querySelectorAll("[name='redis-cache-update']").forEach(button => {
        button.addEventListener("click", function (event) {
            event.preventDefault();
            let button = this;
            let cache = this.getAttribute("data-cache");

            if (button.disabled === true) {
                return;
            }

            button.disabled = true;
            button.textContent = "Updating...";

            fetch(ajaxurl, {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: `action=rdg_blocks_update_cache&cache=${cache}`,
            })
            .then((response) => response.text())
            .then((resultado) => {
                let idSelector = `api_response_item_${cache}`.replace(/:/g, "\\:");
                document.querySelector('.' + idSelector + ' pre').innerHTML = resultado;

                button.disabled = false;
                button.textContent = "Update";
            })
            .catch((err) => console.error(err));
        });
    });

    document.querySelectorAll("select.filter_cache").forEach(select => {
        select.addEventListener("change", function () {
            let url = new URL(window.location.href);

            document.querySelectorAll("select.filter_cache").forEach(sel => {
                let paramName = sel.id;
                let paramValue = sel.value;

                if (paramValue && paramValue !== "") {
                    url.searchParams.set(paramName, paramValue);
                } else {
                    url.searchParams.delete(paramName);
                }
            });

            window.location.href = url.toString();
        });
    });

    document.querySelector("[name='redis-cache-delete-all']").addEventListener("click", function (event) {
        event.preventDefault();

        let button = this;
        if (button.disabled === true) {
            return;
        }

        const confirmed = confirm("Are you sure you want to continue?");
        if (!confirmed) {
            return;
        }

        button.disabled = true;
        button.textContent = "Deleting All...";
        let url = new URL(window.location.href);

        fetch(ajaxurl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "action=rdg_blocks_delete_cache_all",
        })
        .then(response => response.text())
        .then(result => {
            button.disabled = false;
            button.textContent = "Delete All";
            
            if (result == 'success') {
                window.location.href = url.toString();
            }
        })
        .catch((err) => console.error(err));
    });

    document.querySelector("[name='redis-cache-filter-clear']").addEventListener("click", function (event) {
        event.preventDefault();

        const paramsToKeep = ["page"];
        const currentUrl = new URL(window.location.href);
        const newUrl = new URL(currentUrl.origin + currentUrl.pathname);

        paramsToKeep.forEach(param => {
            const value = currentUrl.searchParams.get(param);
            if (value !== null) {
                newUrl.searchParams.set(param, value);
            }
        });

        window.location.href = newUrl.toString();
    });

    document.querySelector("[name='redis-cache-delete-selected']").addEventListener("click", function (event) {
        event.preventDefault();

        let selectedItems = Array.from(document.querySelectorAll(".filters_cache_data tbody tr")).map(tr => tr.className);
        if (selectedItems.length === 0) {
            return;
        }

        let button = this;
        if (button.disabled === true) {
            return;
        }

        const confirmed = confirm("Are you sure you want to continue?");
        if (!confirmed) {
            return;
        }

        button.disabled = true;
        button.textContent = "Deleting Selected...";
        let url = new URL(window.location.href);

        fetch(ajaxurl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "action=rdg_blocks_delete_cache_selected&selected=" + selectedItems,
        })
        .then(response => response.text())
        .then(result => {
            button.disabled = false;
            button.textContent = "Delete Selected";
            window.location.href = url.toString();
        })
        .catch((err) => console.error(err));
    });

    function populateSelect(selectId, data, selectedValue) {
        let select = document.getElementById(selectId);
        if (!select) return;

        select.innerHTML = "";

        let defaultOption = document.createElement("option");
        defaultOption.value = "";
        defaultOption.textContent = "Select an option";
        select.appendChild(defaultOption);

        data.forEach(item => {
            let option = document.createElement("option");
            option.value = item;
            option.textContent = item;
            select.appendChild(option);

            if (selectedValue && selectedValue === item) {
                option.selected = true;
            }

            select.appendChild(option);
        });
    }

    populateSelect("filter_type", jsonData.data_filter_type, jsonData.selected.filter_type);
    populateSelect("filter_type_id", jsonData.data_filter_type_ids, jsonData.selected.filter_type_id);
    populateSelect("filter_block_type", jsonData.data_filter_block_types, jsonData.selected.filter_block_type);
    populateSelect("filter_block_status", jsonData.data_filter_block_status, jsonData.selected.filter_block_status);
});

