"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const uikit_1 = require("@gravity-ui/uikit");
const ErrorWrapper_1 = tslib_1.__importDefault(require("../../components/ErrorWrapper/ErrorWrapper.js"));
const cn_1 = require("../../utils/cn.js");
const i18n_1 = require("./i18n/index.js");
const b = (0, cn_1.block)('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 ((0, jsx_runtime_1.jsx)("div", { className: b('loader'), children: (0, jsx_runtime_1.jsx)(uikit_1.Spin, { size: "xl" }) }));
    }
    return ((0, jsx_runtime_1.jsx)(ErrorWrapper_1.default, { isError: error, text: (0, i18n_1.i18n)('loadable-load-error'), buttonText: (0, i18n_1.i18n)('loadable-try-again'), handler: onTryAgain, children: (0, jsx_runtime_1.jsx)(Component, { ...block, children: data &&
                (Array.isArray(data) ? (data.map((componentData, index) => ((0, jsx_runtime_1.jsx)(ChildComponent, { ...componentData }, componentData.id || index)))) : ((0, jsx_runtime_1.jsx)(ChildComponent, { ...data }))) }) }));
};
exports.default = Loadable;
//# sourceMappingURL=Loadable.js.map
