import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';

import styles from './ReactList.module.scss';

function ReactList({ length, pageSize = 10, itemRenderer, threshold = 100, ...otherProps }) {
  const containerRef = useRef(null);
  const [visibleCount, setVisibleCount] = useState(pageSize);

  const checkScroll = (el) => {
    if (!el) return;

    const { scrollTop, clientHeight, scrollHeight } = el;
    const computedStyle = window.getComputedStyle(el);
    const paddingTop = parseFloat(computedStyle.paddingTop) || 0;
    const paddingBottom = parseFloat(computedStyle.paddingBottom) || 0;

    if (scrollHeight <= scrollTop + clientHeight + threshold + paddingTop + paddingBottom) {
      setVisibleCount((prev) => Math.min(prev + pageSize, length));
    }
  };

  return (
    <div
      {...otherProps}
      ref={containerRef}
      onScroll={(event) => checkScroll(event.target)}
      className={classNames(otherProps.className, styles.Content)}
    >
      {Array.from({ length: Math.min(visibleCount, length) }, (_, i) => itemRenderer(i))}
    </div>
  );
}

ReactList.propTypes = {
  length: PropTypes.number.isRequired,
  pageSize: PropTypes.number,
  itemRenderer: PropTypes.func.isRequired,
  threshold: PropTypes.number,
};

export default ReactList;
