import $ from "jquery";
import { useLayoutEffect, useRef } from "react";

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

const useCookieGroupTabSortable = (enabled: boolean) => {
    const ref = useRef<HTMLDivElement>();
    const { cookieStore } = useStores();
    const {
        groups: {
            entries: { size },
        },
        essentialGroup,
    } = cookieStore;

    useLayoutEffect(() => {
        if (ref.current && enabled && size > 1) {
            const $elem = $(ref.current).find(".rcb-antd-tabs-nav-wrap > div:first");
            $elem.sortable({
                items: "> .rcb-antd-tabs-tab",
                helper: "clone",
                cancel: "",
                axis: "x",
                start: (e, ui) => {
                    ui.placeholder.height("auto");
                },
                update: () => {
                    const ids = $elem
                        .find("> div > [aria-controls]")
                        .toArray()
                        .map((obj) => +obj.getAttribute("aria-controls").split("-").pop());
                    cookieStore.groups.orderCookieGroups(ids);
                },
            });
            return () => $elem.sortable("destroy");
        }
        return () => {
            // Silence is golden.
        };
    }, [ref.current, size, cookieStore, essentialGroup]);

    return ref;
};

export { useCookieGroupTabSortable };
