import $ from "jquery";
import { useCallback, useEffect, useMemo } from "react";

import type { ToolbarButtonProps } from "@devowl-wp/react-folder-tree";
import { Popconfirm } from "@devowl-wp/react-folder-tree";

import { useStores } from "../../store/stores.js";
import { __ } from "../../utils/i18n.js";

function useSortMode() {
    const { optionStore } = useStores();
    const {
        others: { editOrder, editOrderBy },
    } = optionStore;

    /**
     * A jQuery object selecting the byorder link above the wp list table.
     */
    const getByOrderLink = useCallback(() => $("ul.subsubsub li.byorder"), []);
    const isOrderModeAvailable = useMemo(() => !!getByOrderLink().length, []); // If true there is a sort mode available.
    const isOrderModeActive = useMemo(
        () =>
            isOrderModeAvailable &&
            editOrderBy.toLowerCase() === "menu_order title" &&
            editOrder.toLowerCase() === "asc",
        [],
    );

    // Deactivate Simple Page Ordering initially
    useEffect(() => {
        !isOrderModeActive && ($(".wp-list-table tbody.ui-sortable") as any).sortable("destroy");
    }, []);

    /**
     * When opening the order symbol show a hint when the plugin is not installed / activated
     * or the pages can not be ordered (no hierarchy).
     */
    const handleOrderModifier: ToolbarButtonProps["modifier"] = useCallback(
        (body) => {
            if (!isOrderModeAvailable) {
                const {
                    others: { simplePageOrdering },
                } = optionStore;
                if (!simplePageOrdering) {
                    // Install plugin
                    body = (
                        <Popconfirm
                            placement="bottom"
                            overlayStyle={{ maxWidth: 254 }}
                            onConfirm={async () => {
                                await optionStore.installAndActivateRealCustomPostOrder();
                                window.location.reload();
                            }}
                            title={__(
                                'If you want to use the custom order functionality for this post type, you need to install and activate the free plugin "Real Custom Post Order".',
                            )}
                            okText={__("Install plugin")}
                            cancelText={__("Cancel")}
                        >
                            {body}
                        </Popconfirm>
                    );
                } else {
                    // Post type can not be reordered
                    body = (
                        <Popconfirm
                            placement="bottom"
                            overlayStyle={{ maxWidth: 254 }}
                            onConfirm={() =>
                                window.open("https://wordpress.org/plugins/simple-page-ordering/#faq-header", "_blank")
                            }
                            title={__(
                                '"Simple Page Ordering" is not available here. You can only reorder post types with hierarchical structure and an "Order" attribute.',
                            )}
                            okText={__("Learn more")}
                            cancelText={__("Cancel")}
                        >
                            {body}
                        </Popconfirm>
                    );
                }
            }

            return body;
        },
        [isOrderModeAvailable, optionStore],
    );

    /**
     * When clicking the order button check if ordering is possible here and
     * redirect to the given parameterized url.
     */
    const handleOrderClick: ToolbarButtonProps["onClick"] = useCallback(() => {
        isOrderModeAvailable && (window.location.href = getByOrderLink().find("a").attr("href"));
    }, []);

    /**
     * Detects automatically if Simple Page Ordering is currently open and
     * cancel with a given parameterized url.
     */
    const handleOrderCancel: ToolbarButtonProps["onCancel"] = useCallback(() => {
        const builder = new URL(window.location.href);
        const { searchParams } = builder;
        searchParams.delete("orderby");
        searchParams.delete("order");
        builder.search = `?${searchParams}`;
        window.location.href = builder.toString();
    }, []);

    return { isOrderModeAvailable, isOrderModeActive, handleOrderModifier, handleOrderClick, handleOrderCancel };
}

export { useSortMode };
