import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { Spin } from '@gravity-ui/uikit';
import ErrorWrapper from "../../components/ErrorWrapper/ErrorWrapper.js";
import { block as blockCn } from "../../utils/cn.js";
import { i18n } from "./i18n/index.js";
import './Loadable.css';
const b = blockCn('loadable-block');
const initData = {
    loading: false,
    error: false,
};
const Loadable = (props) => {
    const { Component, ChildComponent, fetch, block, blockKey, serviceId, params } = props;
    const [dataState, setDataState] = React.useState(initData);
    const [refetchIndex, setRefetchIndex] = React.useState(0);
    const onTryAgain = React.useCallback(() => {
        setRefetchIndex(refetchIndex + 1);
    }, [refetchIndex]);
    React.useEffect(() => {
        async function processData() {
            setDataState({ loading: true, error: false });
            let data, error;
            try {
                data = await fetch({ blockKey, serviceId, ...(params ?? {}) });
                error = false;
                setDataState({ data, loading: false, error });
            }
            catch (ex) {
                error = true;
                setDataState({ loading: false, error });
            }
        }
        processData();
    }, [refetchIndex, fetch, blockKey, serviceId, params]);
    const { error, loading, data } = dataState;
    if (loading) {
        return (_jsx("div", { className: b('loader'), children: _jsx(Spin, { size: "xl" }) }));
    }
    return (_jsx(ErrorWrapper, { isError: error, text: i18n('loadable-load-error'), buttonText: i18n('loadable-try-again'), handler: onTryAgain, children: _jsx(Component, { ...block, children: data &&
                (Array.isArray(data) ? (data.map((componentData, index) => (_jsx(ChildComponent, { ...componentData }, componentData.id || index)))) : (_jsx(ChildComponent, { ...data }))) }) }));
};
export default Loadable;
//# sourceMappingURL=Loadable.js.map
