import React, { useRef, useState } from 'react';
import {
  FlatList,
  NativeSyntheticEvent,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  ViewStyle,
} from 'react-native';
import { colors } from '../../theme/theme';
import { heightPercentageToDP, widthPercentageToDP } from '../../utils';
import type { IOnBoardingProps } from './onboarding';
import { Footer } from './Footer';
import { Slide } from './Slide';

export const OnBoarding = ({ data, handleFinish }: IOnBoardingProps) => {
  const [currentSlideIndex, setCurrentSlideIndex] = useState(0);
  const ref = useRef<any>();

  const updateCurrentSlideIndex = (e: NativeSyntheticEvent<any>) => {
    const contentOffsetX = e.nativeEvent.contentOffset.x;
    const currentIndex = Math.round(
      contentOffsetX / widthPercentageToDP('100%')
    );
    setCurrentSlideIndex(currentIndex);
  };

  const goToPrevSlide = () => {
    const PrevSlideIndex = currentSlideIndex - 1;
    if (PrevSlideIndex >= 0) {
      const offset = PrevSlideIndex * widthPercentageToDP('100%');
      ref?.current.scrollToOffset({ offset });
      setCurrentSlideIndex(currentSlideIndex - 1);
    }
  };

  const goToNextSlide = () => {
    const nextSlideIndex = currentSlideIndex + 1;
    if (nextSlideIndex !== data.length) {
      const offset = nextSlideIndex * widthPercentageToDP('100%');
      ref?.current.scrollToOffset({ offset });
      setCurrentSlideIndex(currentSlideIndex + 1);
    }
  };

  return (
    <SafeAreaView style={styles.SafeAreaView}>
      <StatusBar backgroundColor={colors.white} />
      <FlatList
        ref={ref}
        data={data}
        pagingEnabled
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={{ height: heightPercentageToDP('100%') - 150 }}
        renderItem={({ item, index }) => (
          <Slide item={item} index={index} length={data.length} />
        )}
        onMomentumScrollEnd={updateCurrentSlideIndex}
      />
      <Footer
        handlePrev={goToPrevSlide}
        handleNext={goToNextSlide}
        handleFinish={handleFinish}
        currentSlideIndex={currentSlideIndex}
        totalSlides={data.length}
      />
    </SafeAreaView>
  );
};

type Style = {
  SafeAreaView: ViewStyle;
};

const styles = StyleSheet.create<Style>({
  SafeAreaView: { flex: 1, backgroundColor: colors.white },
});
