import { isValidElement, useCallback, useEffect, useRef, useState, } from 'react';
export const useLogic = ({ aside, header, formProps, }) => {
    const [headerActions, setHeaderActions] = useState(undefined);
    const containerRef = useRef(null);
    const getHeaderProps = () => {
        if (!isValidElement(header)) {
            // biome-ignore lint/nursery/noShadow: <>
            const { actions, ...restHeaderProps } = header;
            return { actions, restHeaderProps };
        }
        return { actions: undefined, restHeaderProps: undefined };
    };
    const { actions, restHeaderProps } = getHeaderProps();
    const { isSubmitting } = formProps.form?.formState || {};
    const isDisabled = formProps.isDisabled ||
        Boolean([...(actions?.main || []), ...(formProps.secondaryActions || [])].find((action) => action.isBlockingOperation && action.loading));
    const updateActions = useCallback((items) => items?.map((item) => ({
        ...item,
        disabled: isSubmitting || isDisabled ? true : item.disabled,
    })), [isSubmitting, isDisabled]);
    useEffect(() => {
        if (!actions) {
            setHeaderActions(undefined);
            return;
        }
        setHeaderActions({
            main: updateActions(actions?.main),
            secondary: updateActions(actions?.secondary),
            secondaryVisible: updateActions(actions?.secondaryVisible),
        });
    }, [actions, isSubmitting, isDisabled]);
    return {
        headerProps: {
            actions: headerActions,
            ...restHeaderProps,
        },
        pageContentProps: {
            isSeparatorShown: Boolean(aside),
        },
        renderChildrenProps: {
            isDisabled: isDisabled || isSubmitting,
            containerRef,
        },
        headerActions,
    };
};
