import { useCallback, useEffect, useRef, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { getWorkbox } from "../../services/contentService";
import { buildWorkboxDescriptorRequest } from "./workboxDescriptors";
function getDescriptorKey(item) {
    return [
        item.id?.toLowerCase() ?? "",
        item.language?.toLowerCase() ?? "",
        item.version ?? 0,
        item.database?.toLowerCase() ?? "",
    ].join("|");
}
function getWorkboxRequestKey(request) {
    const itemsKey = request.items.map(getDescriptorKey).sort().join(",");
    const renderedItemsKey = request.renderedItems
        .map(getDescriptorKey)
        .sort()
        .join(",");
    return `${itemsKey}::${renderedItemsKey}`;
}
export function useWorkbox(params) {
    const { page, currentItemDescriptor, validate } = params;
    const [workboxItems, setWorkboxItems] = useState([]);
    const [isWorkboxLoading, setIsWorkboxLoading] = useState(false);
    const requestIdRef = useRef(0);
    useEffect(() => {
        if (!workboxItems || workboxItems.length === 0)
            return;
        const itemsToValidate = workboxItems.map((x) => x.item);
        validate(itemsToValidate);
    }, [workboxItems, validate]);
    const loadWorkbox = useCallback(async (items, renderedItems, requestId) => {
        if (!items.length && !renderedItems.length) {
            if (requestIdRef.current === requestId) {
                setWorkboxItems([]);
                setIsWorkboxLoading(false);
            }
            return;
        }
        try {
            const workbox = await getWorkbox({
                items,
                renderedItems,
            });
            if (requestIdRef.current !== requestId)
                return;
            const results = workbox.data || [];
            const sorted = results.sort((a, b) => {
                if (a.isPublished === b.isPublished)
                    return ((b.workflowCommands?.length || 0) -
                        (a.workflowCommands?.length || 0));
                return !a.isPublished || !a.isPublishable ? -1 : 1;
            });
            setWorkboxItems(sorted);
        }
        catch (error) {
            if (requestIdRef.current !== requestId)
                return;
            console.error("Error loading workbox:", error);
            setWorkboxItems([]);
        }
        finally {
            if (requestIdRef.current === requestId) {
                setIsWorkboxLoading(false);
            }
        }
    }, []);
    const loadWorkboxDebounced = useDebouncedCallback((items, renderedItems, requestId) => {
        loadWorkbox(items, renderedItems, requestId);
    }, 500);
    const request = buildWorkboxDescriptorRequest(page, currentItemDescriptor);
    const requestKey = getWorkboxRequestKey(request);
    const requestRef = useRef(request);
    requestRef.current = request;
    /**
     * Re-fetches workbox state for the current descriptors (e.g. when a publish
     * operation completes). Does not toggle isWorkboxLoading: a background
     * refresh should update the list in place instead of blanking it.
     */
    const refreshWorkbox = useCallback(() => {
        const requestId = requestIdRef.current + 1;
        requestIdRef.current = requestId;
        loadWorkboxDebounced.cancel(); // a pending debounced call would carry a stale requestId
        loadWorkbox(requestRef.current.items, requestRef.current.renderedItems, requestId);
    }, [loadWorkbox, loadWorkboxDebounced]);
    useEffect(() => {
        const requestId = requestIdRef.current + 1;
        requestIdRef.current = requestId;
        setIsWorkboxLoading(request.items.length > 0 || request.renderedItems.length > 0);
        loadWorkboxDebounced(request.items, request.renderedItems, requestId);
        return () => loadWorkboxDebounced.cancel();
    }, [requestKey]);
    return { workboxItems, isWorkboxLoading, refreshWorkbox };
}
//# sourceMappingURL=useWorkbox.js.map