import $ from "jquery";
import { useCallback } from "react";

import type { TreeNodeId, TreeNodeProps } from "@devowl-wp/react-folder-tree";

import { loadFastModeContent } from "../../others/fastModeContent.js";
import { useStores } from "../../store/stores.js";
import { TreeStore } from "../../store/tree.js";
import { addUrlParam } from "../../utils/addUrlParam.js";
import { urlParam } from "../../utils/urlParam.js";

import type { CategoryNode } from "../../models/categoryNode.js";

/**
 * A node gets selected. Depending on the fast mode the page gets reloaded
 * or the wp list table gets reloaded.
 */
function useHandleSelect(
    toolbarActiveButton: string,
    isOrderModeActive: boolean,
    fastModeContentLoaded?: () => void,
): (id: TreeNodeId) => void {
    const { optionStore, treeStore } = useStores();

    const handleSelect: TreeNodeProps["onSelect"] = useCallback(
        async (id) => {
            const {
                others: {
                    typenow,
                    screenSettings: { isFastMode },
                },
            } = optionStore;

            // If sorting no action is allowed and not already selected
            if (toolbarActiveButton === "sort") {
                return;
            }

            // Generate URL with query args
            let url = window.location.href;
            if (id === TreeStore.ID_ALL) {
                url = addUrlParam(window.location.pathname, "post_type", typenow);
            } else {
                const node = treeStore.byId(+id);
                $.each(node.properties.queryArgs, (key, value) => {
                    url = addUrlParam(url, key as string, value);
                });
            }
            +urlParam("paged") > 1 && (url = addUrlParam(url, "paged", 1));

            // Update busy state for selected item
            const node = treeStore.byId(id as CategoryNode["id"], false);
            node.setSelected(true);

            if (isFastMode && !isOrderModeActive) {
                // Fast mode active so load URL and get content
                node.setBusy(false);
                setTimeout(() => loadFastModeContent(url).then(fastModeContentLoaded));
            } else {
                window.location.href = url;
                node.setBusy(true);
            }
        },
        [toolbarActiveButton, optionStore],
    );

    return handleSelect;
}

export { useHandleSelect };
