import { FlatList, FlatListProps } from 'react-native'
import { useTabContext } from './Context'
import React from 'react'

type TabListProps = Omit<FlatListProps<any>, 'data' | 'renderItem'>

/**
 * Tab children are passed as JSX children (not a `data` array), converted via
 * `React.Children.toArray` and fed into a horizontal FlatList. The FlatList ref is shared from
 * context so `Tab` can programmatically scroll to the active tab on selection.
 */
export const TabList = (props: TabListProps) => {
  const { children, ...flatListProps } = props

  const { styles, flatListRef } = useTabContext()

  const childrenArray = React.Children.toArray(children)

  return (
    <FlatList
      horizontal
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      {...flatListProps}
      ref={flatListRef}
      data={childrenArray}
      renderItem={({ item }) => item}
      keyExtractor={(_, index) => `tab-${index}`}
      style={styles?.tabList}
      contentContainerStyle={styles?.tabListContainer}
    />
  )
}