import React, {useEffect, useRef, useState} from 'react';
import {FlatList, StyleSheet, Text, useWindowDimensions} from 'react-native';
import RNFS from 'react-native-fs';
import CardAyatList from '../../components/CardAyatList/CardAyatList.component';
import Loading from '../../components/loading/loading.component';
import {RootStackScreenProps} from '../../navigation/AppNavigator';
import {useAppSelector} from '../../store/hooks';
import {colors} from '../../themes/colors';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Separator} from '../../components/separator/separator.component';

const QuranDetailScreen = ({
  route: {
    params: {id, data},
  },
}: RootStackScreenProps<'QuranDetail'>) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------
  const {height} = useWindowDimensions();
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const flatListRef = useRef<FlatList>(null);
  const [scrollPosition, setScrollPosition] = useState(0);
  const {error, loading, refreshing} = useAppSelector(state => state.quranList);

  // ---------------------------------------------------------------------------
  // useEffect
  // ---------------------------------------------------------------------------

  useEffect(() => {
    // Retrieve scroll position when component mounts
    const retrieveScrollPosition = async () => {
      try {
        const savedScrollPosition = await AsyncStorage.getItem(
          'scrollPosition',
        );
        console.log('savedScrollPosition', savedScrollPosition);
        if (savedScrollPosition !== null) {
          setScrollPosition(parseInt(savedScrollPosition, 10));
          if (flatListRef.current) {
            flatListRef.current.scrollToOffset({
              offset: parseInt(savedScrollPosition, 10),
              animated: false,
            });
          }
        }
      } catch (error) {
        console.error('Error retrieving scroll position:', error);
      }
    };

    retrieveScrollPosition();
  }, [flatListRef.current]);

  useEffect(() => {
    const checkDiskSpace = async () => {
      try {
        const info = await RNFS.getFSInfo();
        const {freeSpace} = info;
        console.log('Free space on the device:', freeSpace);
      } catch (error) {
        console.log('Error checking disk space:', error);
      }
    };

    checkDiskSpace();
  }, []);

  // ---------------------------------------------------------------------------
  // functions
  // ---------------------------------------------------------------------------
  const itemsPerPage = 10;
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;

  
  let ITEM_HEIGHT = 600;
 
  const handleScroll = (event: any) => {
    // Update scroll position when scrolling
    const currentPosition = event.nativeEvent.contentOffset.y;
    setScrollPosition(currentPosition);
    // Save scroll position to AsyncStorage
    console.log('====================================');
    console.log('currentPosiition', currentPosition);
    console.log('====================================');
    AsyncStorage.setItem('scrollPosition', currentPosition.toString());
  };

  const loadMoreData = () => {
    if (endIndex < data.verses.length) {
      setCurrentPage(currentPage + 1);
    }
  };

  const renderData = () => {
    if (isLoading) {
      return <Loading />;
    }
    if (!data) {
      return <Text>No Data Found!</Text>;
    }
    return (
      <FlatList
        style={styles.container}
        ref={flatListRef}
        onScroll={handleScroll}
        data={data.verses}
        renderItem={({item}) => (
          <CardAyatList
            data={{
              ...data,
              verses: [item],
            }}
            onPress={() => {}}
          />
        )}
        keyExtractor={(item, index) => index.toString()}
        ItemSeparatorComponent={Separator}
        onEndReached={loadMoreData}
        onEndReachedThreshold={0.5}
        scrollEventThrottle={160}
      />
    );
  };
  // ---------------------------------------------------------------------------
  return renderData();
};

export default QuranDetailScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.white,
  },
});
it is scrolling good until currentPosition becomes 5349 but when I scroll more than 5349 and navigate away from component then returning back to component it reset to 5349. How to fix that current position not reset to 5349 for example when current position is 7000 then I navigate away and return to component the savedScrollPosition shows 7000 but current position resets to 5349 ?