import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import AdaptiveContainer from "../AdaptiveContainer";
import useAsyncControl from "../../hooks/useAsyncControl";
import { Fragment, useEffect, useInsertionEffect, useState, } from "react";
import Styles from "./AsyncTriggerContainer.module.scss";
import Button from "../Button";
import { useOneUIConfig } from "../../context/OneUIProvider";
/**
 * Wraps a component, triggers the provided action onMount, shows loading, and if the action fails and rejects handles the UI for error.
 * Do not use try catch on the action as this component already handles rejections.
 *
 * @example
 * <AsyncTriggerContainer action={anAsyncProcess}>
 *  <>This is only shown when the action finished successfully</>
 * </AsyncTriggerContainer>
 */
/**
 * A component that manages the lifecycle of an asynchronous operation.
 * It displays a loading state while the operation runs, shows the child content
 * when the operation succeeds, and provides a retry option if the operation fails.
 */
export default function AsyncTriggerContainer({ action, children, loadingLabel, className, style, }) {
    const [executed, setExecuted] = useState(false);
    const control = useAsyncControl({
        action: () => action().then(() => setExecuted(true)),
    });
    useEffect(() => {
        if (action)
            control.action();
    }, [action]);
    useInsertionEffect(() => {
        if (action)
            control.loading = true;
    }, [action]);
    /**
     * For the future:
     * If we ever have a way to recall the function, we could display the loader again, but on a absolute position at the bottom of the page, when it already executed
     */
    return (_jsx(AsyncTriggerContainerView, { className: className, style: style, children: children, showContent: executed, loadingLabel: loadingLabel, control: control }));
}
export function AsyncTriggerContainerView({ className, children, style, showContent, control, loadingLabel, }) {
    const Loading = useOneUIConfig("component.asyncTriggerContainer.LoadingComponent");
    const retry = (_jsx(Fragment, { children: _jsx(Button, { onClick: () => control.action(), children: "Retry" }) }, "error"));
    const loading = (_jsx(Fragment, { children: loadingLabel || _jsx(Loading, {}) }, "loading"));
    return (_jsx(AdaptiveContainer, { contentClassName: `${className} relative`, direction: "v", style: style, className: Styles.container, children: showContent ? (_jsxs(Fragment, { children: [children, _jsx(AdaptiveContainer, { direction: "both", className: Styles.loader, contentClassName: Styles.loaderContainer, children: control.error ? (retry) : control.loading ? (loading) : (_jsx(Fragment, {}, "no")) })] }, "executed")) : control.error ? (retry) : control.loading ? (loading) : (_jsx(Fragment, {}, "not_exec")) }));
}
//# sourceMappingURL=AsyncTriggerContainer.js.map