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,
      });
    }
  }, [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,
  },
});
import {createSlice, PayloadAction, createAsyncThunk} from '@reduxjs/toolkit';
import {persistReducer, persistStore} from 'redux-persist';
import RNFS, {writeFile, readFile} from 'react-native-fs';

import {RootState} from '../index';
import {SurahType} from '../../types/surah';
import surahData from '../../assets/quran-json/quran-ru.json';

interface initialStateInterface {
  data: SurahType[];
  error: boolean;
  errorMessage: string;
  loading: boolean;
  refreshing: boolean;
  position: number;
}

const initialState: initialStateInterface = {
  data: [],
  loading: true,
  error: false,
  errorMessage: '',
  refreshing: false,
  position: 0,
};

export const fetchQuranList = createAsyncThunk(
  'quranList/fetchQuranList',
  async () => {
    const filePath = `${RNFS.DocumentDirectoryPath}/quranList.json`;
    const fileExists = await RNFS.exists(filePath);

    if (fileExists) {
      const cachedData = await readFile(filePath, 'utf8');
      return JSON.parse(cachedData);
    } else {
      const data = (surahData as SurahType[]).map(surah => ({
        id: surah.id,
        name: surah.name,
        transliteration: surah.transliteration,
        translation: surah.translation,
        type: surah.type,
        verses: surah.verses,
        number_of_ayah: surah.number_of_ayah,
        total_verses: surah.total_verses,
      })) as SurahType[];

      await writeFile(filePath, JSON.stringify(data), 'utf8');
      return data;
    }
  },
);

export const quranListSlice = createSlice({
  name: 'quranList',
  initialState,
  reducers: {
    setQuranPosition: (state, action: PayloadAction<number>) => {
      state.position = action.payload;
    },
  },
  extraReducers: builder => {
    builder
      .addCase(fetchQuranList.pending, state => {
        state.loading = true;
        state.error = false;
        state.errorMessage = '';
        state.refreshing = true;
      })
      .addCase(fetchQuranList.fulfilled, (state, action) => {
        state.data = action.payload;
        state.loading = false;
        state.refreshing = false;
      })
      .addCase(fetchQuranList.rejected, (state, action) => {
        console.log('action.error', action.error);

        state.loading = false;
        state.error = true;
        state.errorMessage = action.error.message ?? 'Something went wrong';
        state.refreshing = false;
      });
  },
});

export const selectQuranData = (state: RootState) => state.quranList.data;
export const selectQuranError = (state: RootState) => state.quranList.error;
export const selectQuranLoading = (state: RootState) => state.quranList.loading;
export const selectQuranPosition = (state: RootState) =>
  state.quranList.position;

export const {setQuranPosition} = quranListSlice.actions;

export default quranListSlice.reducer;
export type SurahType = {
  id: number;
  name: string;
  name_translations: {
    [key: string]: string;
  };
  transliteration: string;
  translation: string;
  number_of_ayah: number;
  number_of_surah: number;
  total_verses: number;
  place: string;
  type: string;
  position: number;
  verses: verse[];
  tafsir: {
    id: {
      kemtjag: {
        name: string;
        source: string;
        text: {
          [key: string]: string;
        };
      };
    };
  };
};

export type verse = {
  id: number;
  introduction: string;
  number: number;
  text: string;
  translation_tj: string;
  translation: string;
};
I have problem with saving verses through id during scrolling. when i quit app and re-enter again it, should open from last place that I quit. How to implement it ?