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 () => {
      const key = `scrollPosition_${data.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,
      });
    }
  }, [data, 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;

  // Save scroll position
  // const handleScroll = (event: any) => {
  //   const yOffset = event.nativeEvent.contentOffset.y;
  //   const key = `scrollPosition_${id}`;
  //   AsyncStorage.setItem(key, yOffset.toString());
  // };

  const handleScroll = (event: any) => {
    const yOffset = event.nativeEvent.contentOffset.y;
    data.verses.forEach(async verse => {
      const key = `scrollPosition_${verse.id}`;
      console.log('key1:', key);

      await 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.slice(0, endIndex)}
        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,
  },
});
Given that data.verses is an array and you want to save the scroll position for each verse specifically, you’ll need to adjust your strategy. Instead of trying to use a single scroll position for the entire detail screen, you should save and restore the scroll position more granitularly, potentially at the verse level or ensure you have a method to identify which verse was last in view or most relevant to the user’s last position. However, there’s a challenge with trying to save the scroll position for each data.verses.id directly—your FlatList displays a continuous scrollable view, not individual screens per verse, so it’s not straightforward to save a scroll position for each verse. Instead, you generally save the scroll position of the list view itself. One approach is to determine the verse that was at the top of the screen (or whichever verse is deemed significant according to your design) when the user last interacted with the list or when the user is leaving the screen. You then save the scroll position alongside the identifier for this particular verse, rather than saving a scroll position for every verse. Please implement it ?