'use client'
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso'
import { useRef, useState } from 'react'

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

export default function VirtualList<T = any>(props: VirtualListProps<T>) {
  const {
    data = [],
    itemContent = (index) => <div>{index}</div>,
    virtuosoProps,
    ...restProps
  } = props
  const virtuosoRef = useRef<VirtuosoHandle>(null)
  const [showScrollButton, setShowScrollButton] = useState(false)

  // 滚动到最新消息
  const scrollToBottom = () => {
    virtuosoRef.current?.scrollToIndex({
      index: data.length - 1,
      behavior: 'smooth',
    })
  }

  return (
    <div {...restProps}>
      <Virtuoso
        ref={virtuosoRef}
        alignToBottom={false}
        {...virtuosoProps}
        style={{ height: '100%', ...virtuosoProps?.style }}
        data={data}
        followOutput="smooth"
        initialTopMostItemIndex={data.length - 1}
        atBottomStateChange={(atBottom) => {
          // 当不在底部时显示按钮，在底部时隐藏
          setShowScrollButton(!atBottom)
        }}
        itemContent={(index, item) => itemContent(index, item as any)}
      />

      {/* 回到底部按钮 */}
      {showScrollButton && (
        <div
          onClick={scrollToBottom}
          className="absolute -right-1 bottom-0 z-10 flex h-10 w-10 items-center justify-center rounded-full hover:scale-110 hover:cursor-pointer"
        >
          scroll
        </div>
      )}
    </div>
  )
}
