import { useEffect, useRef, useState } from "react";
import { Empty, Spin } from "@arco-design/web-react";
import "./index.css";

const InfiniteScroll = ({
  loadMore,
  hasMore,
  children,
  threshold = 50,
  className = "",
  empty = false,
}) => {
  const containerRef = useRef(null);
  const [loading, setLoading] = useState(false);

  const handleScroll = () => {
    if (loading) return;
    setLoading(true);
    if (!containerRef.current || !hasMore) return;

    const { scrollTop, scrollHeight, clientHeight } = containerRef.current;

    if (scrollTop + clientHeight >= scrollHeight - threshold) {
      loadMore().finally(() => {
        setLoading(false);
      });
    }
  };

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener("scroll", handleScroll);
      // 初始加载时检查是否需要加载更多
      handleScroll();
    }

    return () => {
      if (container) {
        container.removeEventListener("scroll", handleScroll);
      }
    };
  }, [loadMore, hasMore, threshold]);

  return (
    <div
      ref={containerRef}
      className={`infinite-scroll-container ${className}`}
    >
      {children}

      {!hasMore && empty && (
        <Empty description="暂无数据" className="empty-data" />
      )}
      {/* 滚动加载指示器 */}
      {loading && hasMore && (
        <div className="loading-container">
          <Spin size="small" />
          <span className="loading-text">加载中...</span>
        </div>
      )}
    </div>
  );
};

export default InfiniteScroll;
