import React, {useEffect, useRef, useState} from 'react';
import {FlatList, StyleSheet, Text} 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 [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(() => {
  const getScrollPosition = async () => {
   for (const verse of data.verses) {
    const key = `scrollPosition_${data.id}_${verse.id}`;
    const position = await AsyncStorage.getItem(key);
    if (position !== null) {
     setScrollPosition(parseFloat(position));
    }
   }
  };

  getScrollPosition();
 }, [id]);

 useEffect(() => {
  // Restore scroll position when component is mounted
  if (flatListRef.current && scrollPosition) {
   flatListRef.current.scrollToOffset({
    offset: scrollPosition,
    animated: false,
   });
  }
 }, [scrollPosition]);

 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) => {
  const yOffset = event.nativeEvent.contentOffset.y;
  const visibleIndex = Math.floor(yOffset / ITEM_HEIGHT); // Assuming ITEM_HEIGHT is constant
  if (visibleIndex >= 0 && visibleIndex < data.verses.length) {
   const visibleVerse = data.verses[visibleIndex];
   console.log('visibleVerse', visibleVerse);

   const key = `scrollPosition_${data.id}_${visibleVerse.id}`; // Incorporate data's ID into the key
   AsyncStorage.setItem(key, yOffset.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={16}
   />
  );
 };
 // ---------------------------------------------------------------------------
 return renderData();
};

export default QuranDetailScreen;

const styles = StyleSheet.create({
 container: {
  flex: 1,
  backgroundColor: colors.white,
 },
});
how to persist only the last scroll position when leaving or quitting the screen ?