import { View, FlatList, Image, Dimensions } from "react-native";
import React, { useEffect, useRef, useState } from "react";
import { DataItem, Props } from "./Banner.types";
import { styles } from "./Banner.styles";

const { width, height } = Dimensions.get("window");

const Banner = (Props: Props) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const FlatListRef = useRef<FlatList<any> | null>(null);

  //Auto Slide
  useEffect(() => {
    let intervel = setTimeout(() => {
      if (activeIndex === Props.data.length - 1) {
        FlatListRef.current?.scrollToIndex({
          index: 0,
          animated: true,
        });
      } else {
        FlatListRef.current?.scrollToIndex({
          index: activeIndex + 1,
          animated: true,
        });
      }
    }, 2000);
    return () => clearTimeout(intervel);
  }, [activeIndex]);

  //display Data
  const renderItem = ({ item, index }: { item: DataItem; index: number }) => {
    return (
      <View style={[styles.mainViewStyle, Props.mainViewStyle]} key={index}>
        <Image
          source={
            typeof item.image === "string" ? { uri: item.image } : item.image
          }
          style={[styles.imageStyle, Props.imageStyle]}
        />
      </View>
    );
  };

  //Render Dot
  const renderDot = () => {
    return Props.data.map((e, index) => (
      <View
        key={index}
        style={[
          styles.dotStyle,
          { backgroundColor: activeIndex == index ? "black" : "grey" },
          Props.dotStyle,
        ]}
      ></View>
    ));
  };

  //HandleScroll
  const handleScroll = (event) => {
    // get The Scroll Position
    //get the index of current active item

    if (event) {
      const slide = Number(event.nativeEvent.contentOffset.x);
      const index = Math.round(slide / width);

      setActiveIndex(index);
    }
  };

  return (
    <View
      style={{
        height: height / 4,
      }}
    >
      <FlatList
        data={Props.data}
        ref={FlatListRef}
        renderItem={renderItem}
        showsHorizontalScrollIndicator={false}
        horizontal={true}
        pagingEnabled={true}
        onScroll={handleScroll}
        keyExtractor={(item) => item.id + ""}
      />
      <View style={[styles.dotViewStyle, Props.dotViewStyle]}>
        {renderDot()}
      </View>
    </View>
  );
};

export default Banner;
