import { useCallback, useEffect, useState } from "react";

import { STATUS_EVENT } from "../types/events/status.js";
import { getStaticOptions } from "../utils/options.js";

import type { StatusEvent } from "../types/events/status.js";
import type { ResponseRouteStatusGet } from "../wp-api/status.get.js";

/**
 * Listen to the queue status and automatically create a state with the errors.
 */
function useStatusErrors() {
    const [, setPreviousHash] = useState<string>();
    const [errors, setErrors] = useState<ResponseRouteStatusGet["errors"]["list"]>({});

    const applyErrors = useCallback(
        (hash: ResponseRouteStatusGet["errors"]["hash"], list: ResponseRouteStatusGet["errors"]["list"]) =>
            setPreviousHash((previousHash) => {
                if (previousHash !== hash) {
                    setErrors(list);
                    return hash;
                }
                return previousHash;
            }),
        [],
    );

    const listener = useCallback(
        (async ({
            detail: {
                errors: { hash, list },
            },
        }: CustomEvent<StatusEvent>) => {
            applyErrors(hash, list);
        }) as any,
        [],
    );

    useEffect(() => {
        // Initial state
        const { hash, list } = getStaticOptions().errors;
        applyErrors(hash, list);

        document.addEventListener(STATUS_EVENT, listener);
        return () => {
            document.removeEventListener(STATUS_EVENT, listener);
        };
    }, []);

    return { errors };
}

export { useStatusErrors };
