import * as React from 'react'
import { useResizeObserver } from '@bestyled/contrib-common'
import { View, ViewProps } from '@bestyled/primitives'
import { FlatList } from './index'

export interface ScrollerProps extends ViewProps {
  id?: string
  itemCount: number
  data: any[]
  renderItem: ({ item: any, index: number }) => React.ReactNode
  scrollToBottom: boolean
  overscanCount?: number
}

export const Scroller: React.FC<ScrollerProps> = props => {
  const [ref, height] = useResizeObserver()
  const {
    id,
    itemCount,
    renderItem,
    data,
    scrollToBottom,
    overscanCount,
    ...rest
  } = props

  return (
    <View {...rest} ref={ref} itemType="Scroller">
      {itemCount > 0 ? (
        <FlatList
          id={id}
          estimatedItemSize={12}
          data={data}
          height={height}
          itemCount={itemCount}
          overscanCount={overscanCount}
          scrollToIndex={scrollToBottom ? itemCount - 1 : null!}
          scrollToAlignment={scrollToBottom ? ('end' as any) : 'auto'}
          renderItem={renderItem}
        />
      ) : null}
    </View>
  )
}
