import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { getScrollParent } from "@tego/client";
import { useLockFn, useThrottleFn } from "ahooks";
import { Spin } from "antd";
import { useTranslation } from "react-i18next";
import style from "./style.mjs";
function isWindow(element) {
    return element === window;
}
const defaultProps = {
    threshold: 250,
    children: (hasMore, failed, retry)=>/*#__PURE__*/ jsx(InfiniteScrollContent, {
            hasMore: hasMore,
            failed: failed,
            retry: retry
        })
};
const InfiniteScroll = (param)=>{
    let { threshold = defaultProps.threshold, loadMore, children = defaultProps.children, hasMore } = param;
    const { styles } = style();
    const [failed, setFailed] = useState(false);
    const doLoadMore = useLockFn(async (isRetry)=>{
        try {
            await loadMore(isRetry);
        } catch (e) {
            setFailed(true);
            throw e;
        }
    });
    const elementRef = useRef(null);
    const [flag, setFlag] = useState({});
    const nextFlagRef = useRef(flag);
    const [scrollParent, setScrollParent] = useState();
    const { run: check } = useThrottleFn(async ()=>{
        if (nextFlagRef.current !== flag) return;
        if (!hasMore) return;
        const element = elementRef.current;
        if (!element) return;
        if (!element.offsetParent) return;
        const parent = getScrollParent(element);
        setScrollParent(parent);
        if (!parent) return;
        const rect = element.getBoundingClientRect();
        const elementTop = rect.top;
        const current = isWindow(parent) ? window.innerHeight : parent.getBoundingClientRect().bottom;
        if (current >= elementTop - threshold) {
            const nextFlag = {};
            nextFlagRef.current = nextFlag;
            try {
                await doLoadMore(false);
                setFlag(nextFlag);
            } catch (e) {
                console.error(e);
            }
        }
    }, {
        wait: 100,
        leading: true,
        trailing: true
    });
    useEffect(()=>{
        check();
    });
    useEffect(()=>{
        const element = elementRef.current;
        if (!element) return;
        if (!scrollParent) return;
        function onScroll() {
            check();
        }
        scrollParent.addEventListener('scroll', onScroll);
        return ()=>{
            scrollParent.removeEventListener('scroll', onScroll);
        };
    }, [
        scrollParent
    ]);
    async function retry() {
        setFailed(false);
        try {
            await doLoadMore(true);
            setFlag(nextFlagRef.current);
        } catch (e) {
            console.error(e);
        }
    }
    return /*#__PURE__*/ jsx("div", {
        className: styles.infiniteScroll,
        ref: elementRef,
        children: 'function' == typeof children ? children(hasMore, failed, retry) : children
    });
};
const InfiniteScrollContent = (props)=>{
    const { t } = useTranslation();
    const { styles } = style();
    if (!props.hasMore) return /*#__PURE__*/ jsx("span", {
        children: t('no more')
    });
    if (props.failed) return /*#__PURE__*/ jsxs("span", {
        children: [
            /*#__PURE__*/ jsx("span", {
                className: "".concat(styles.infiniteScroll, "-failed-text"),
                children: t('failed to load')
            }),
            /*#__PURE__*/ jsx("a", {
                onClick: ()=>{
                    props.retry();
                },
                children: t('retry')
            })
        ]
    });
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx("span", {
                children: t('loading')
            }),
            /*#__PURE__*/ jsx(Spin, {})
        ]
    });
};
export { InfiniteScroll };
