'use client';

import { cn } from '@/lib/utils';
import { useEffect, useRef, useState } from 'react';

type ItemType<T = any> = {
  type: string;
  data?: T;
};
type VirtualListProps<T = any> = {
  data?: ItemType<T>[];
  itemContent?: (index: number, item: { type: string; data: T }) => React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>;

export default function VirtualList<T = any>(props: VirtualListProps<T>) {
  const { data = [], itemContent = (index) => <div>{index}</div>, ...restProps } = props;
  const ref = useRef<HTMLDivElement>(null);
  const previousData = useRef<ItemType[]>([]);
  const [isUserAtBottom, setIsUserAtBottom] = useState(true);

  // 检查用户是否滚动到底部附近（阈值为 50px）
  const checkIfAtBottom = () => {
    const element = ref.current;
    if (!element) return false;

    const { scrollTop, scrollHeight, clientHeight } = element;
    const threshold = 50; // 距离底部 50px 以内认为是在底部
    return scrollHeight - scrollTop - clientHeight < threshold;
  };

  // 监听用户滚动事件
  const handleScroll = () => {
    const atBottom = checkIfAtBottom();
    setIsUserAtBottom(atBottom);
  };

  // 当数据更新时，只有用户在底部才自动滚动
  useEffect(() => {
    const last = (list: ItemType[]) => (list?.length ? list[list.length - 1] : null);
    const lastChanged = last(previousData.current)?.data !== last(data)?.data;

    if (lastChanged && isUserAtBottom) {
      ref.current?.scrollTo({
        top: ref.current?.scrollHeight,
        behavior: 'smooth',
      });
    }

    previousData.current = data;
  }, [data, isUserAtBottom]);

  return (
    <div
      {...restProps}
      ref={ref}
      onScroll={handleScroll}
      className={cn('overflow-auto', restProps.className)}
    >
      {data.map((item, index) => (
        <div key={index}>{itemContent(index, item as any)}</div>
      ))}
    </div>
  );
}
