import React, { useEffect, useRef, useState, memo } from 'react';
import PropTypes from 'prop-types';

const VirtualList = memo(function VirtualList({
  items,
  height,
  itemHeight,
  renderItem,
  overscan = 3,
  className = '',
  onScroll,
  initialScrollOffset = 0
}) {
  const [scrollTop, setScrollTop] = useState(initialScrollOffset);
  const [viewportHeight, setViewportHeight] = useState(height);
  const containerRef = useRef(null);

  // Вычисляем видимые элементы
  const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
  const endIndex = Math.min(
    items.length - 1,
    Math.ceil((scrollTop + viewportHeight) / itemHeight) + overscan
  );

  // Вычисляем смещение для видимых элементов
  const offsetY = startIndex * itemHeight;

  // Обработчик прокрутки
  const handleScroll = (event) => {
    const newScrollTop = event.target.scrollTop;
    setScrollTop(newScrollTop);
    onScroll?.(newScrollTop);
  };

  // Обновление высоты при изменении размера окна
  useEffect(() => {
    const updateHeight = () => {
      if (containerRef.current) {
        setViewportHeight(containerRef.current.clientHeight);
      }
    };

    updateHeight();
    window.addEventListener('resize', updateHeight);
    return () => window.removeEventListener('resize', updateHeight);
  }, []);

  // Установка начальной позиции прокрутки
  useEffect(() => {
    if (containerRef.current && initialScrollOffset > 0) {
      containerRef.current.scrollTop = initialScrollOffset;
    }
  }, [initialScrollOffset]);

  return (
    <div
      ref={containerRef}
      className={`overflow-auto ${className}`}
      style={{ height }}
      onScroll={handleScroll}
    >
      <div
        style={{
          height: items.length * itemHeight,
          position: 'relative'
        }}
      >
        <div
          style={{
            position: 'absolute',
            top: offsetY,
            left: 0,
            right: 0
          }}
        >
          {items.slice(startIndex, endIndex + 1).map((item, index) => (
            <div
              key={item.id || index}
              style={{
                height: itemHeight,
                position: 'absolute',
                top: index * itemHeight,
                left: 0,
                right: 0
              }}
            >
              {renderItem(item, startIndex + index)}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
});

VirtualList.propTypes = {
  items: PropTypes.array.isRequired,
  height: PropTypes.number.isRequired,
  itemHeight: PropTypes.number.isRequired,
  renderItem: PropTypes.func.isRequired,
  overscan: PropTypes.number,
  className: PropTypes.string,
  onScroll: PropTypes.func,
  initialScrollOffset: PropTypes.number
};

export default VirtualList; 