import OnBoardingSliderItem from "@/components/sliderUi/OnBoardingSliderItem";
import Pagination from "@/components/sliderUi/Pagination";
import SliderButton from "@/components/sliderUi/SliderButton";
import { storage } from "@/configs/storage";
import { router } from "expo-router";
import React, { useState } from "react";
import { FlatList, Pressable, Text, View, ViewToken } from "react-native";
import Animated, { useAnimatedRef, useAnimatedScrollHandler, useSharedValue } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const onbordingSliderData = [1, 2, 3];

const OnBoardingSlider = () => {
  const [currentTheme, setCurrentTheme] = useState<"light" | "dark">("light");
  const insets = useSafeAreaInsets();

  const flatListRef = useAnimatedRef<FlatList>();
  const x = useSharedValue(0);
  const flatListIndex = useSharedValue(0);

  const onViewableItemsChanged = ({ viewableItems }: { viewableItems: ViewToken[] }) => {
    if (viewableItems[0]?.index !== null && viewableItems[0]?.index !== undefined) {
      flatListIndex.value = viewableItems[0].index;
    }
  };

  const onScroll = useAnimatedScrollHandler({
    onScroll: (event) => {
      x.value = event.contentOffset.x;
    },
  });

  return (
    <View className="h-full bg-white  pb-8">
      <View className="flex-1" style={{ zIndex: 1 }}>
        <View className="flex items-center justify-center  flex-1 ">
          <Animated.FlatList
            ref={flatListRef}
            data={onbordingSliderData}
            onScroll={onScroll}
            keyExtractor={(item) => `key:${item}`}
            renderItem={({ item, index }) => {
              return <OnBoardingSliderItem item={item} idx={index} />;
            }}
            scrollEventThrottle={16}
            horizontal={true}
            bounces={false}
            pagingEnabled={true}
            showsHorizontalScrollIndicator={false}
            onViewableItemsChanged={onViewableItemsChanged}
            viewabilityConfig={{
              minimumViewTime: 300,
              viewAreaCoveragePercentThreshold: 10,
            }}
          />
        </View>
        <View className="flex justify-center items-center pt-8">
          <Pagination onbordingSliderData={onbordingSliderData} x={x} />
        </View>
      </View>

      <View
        className=" px-6 absolute left-0 right-0 flex-row justify-between items-center z-20"
        style={{
          bottom: insets.bottom + 32,
        }}
      >
        
        <Pressable
          onPress={async () => {
            storage.set("onboarding", "false");
            router.push("/(auth)/sign-in");
          }}
        >
          <Text className="font-manrope-bold text-lg w-20 text-slate-700">Skip</Text>
        </Pressable>

        <SliderButton flatListRef={flatListRef} flatListIndex={flatListIndex} dataLength={onbordingSliderData.length} x={x} />
      </View>
    </View>
  );
};

export default OnBoardingSlider;
