// Carousel component
// props:
//   - items: array
//   - style: object
//   - itemStyle: object
//   - disabled: boolean
//   - disabledStyle: object
//   - disabledItemStyle: object
//

// import crousel requirements
import React from 'react'
import { View, StyleSheet, Animated, FlatList } from 'react-native'
import { colors } from '../theme'
import { WIDTH } from '../utils'
// create carousel component
const Carousel = ({
  items = [],
  renderItem,
  autoScroll = false,
  timer = 3000,
}) => {
  // handle auto scroll the flatlist every 3 seconds
  const flatListRef = React.useRef()
  const [index, setIndex] = React.useState(0)

  React.useEffect(() => {
    if (!autoScroll) return
    const interval = setInterval(() => {
      flatListRef.current.scrollToIndex({
        animated: true,
        index: index === items.length - 1 ? 0 : index + 1,
      })
      setIndex(index === items.length - 1 ? 0 : index + 1)
    }, timer)
    return () => clearInterval(interval)
  }, [index])

  // create carousel styles
  const styles = StyleSheet.create({
    container: {
      width: '100%',
      height: 200,
    },
    item: {
      width: WIDTH * 0.8,
      height: '100%',
      backgroundColor: colors.primary,
      margin: 10,
    },
    disabled: {
      opacity: 0.5,
    },
  })

  // return carousel
  return (
    <View style={styles.container}>
      <FlatList
        data={items}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
        ref={flatListRef}
      />
    </View>
  )
}

// export carousel
export default Carousel
