use expo-secure-store.

// screens/ExercisesScreen.js

import React, { useEffect, useState, useContext, useCallback } from 'react';
import {
    View,
    Text,
    FlatList,
    Image,
    StyleSheet,
    ActivityIndicator,
    Alert,
    TouchableOpacity,
    Linking,
    TextInput,
    RefreshControl,
} from 'react-native';
import axios from 'axios';
import { AuthContext } from '../context/AuthContext';
import debounce from 'lodash.debounce';
import AsyncStorage from '@react-native-async-storage/async-storage';

const ExercisesScreen = () => {
    const { authToken } = useContext(AuthContext);
    const [exercises, setExercises] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [isRefreshing, setIsRefreshing] = useState(false);

    // Define the cache keys
    const CACHE_KEY = 'cachedExercises';
    const CACHE_TIMESTAMP_KEY = 'cachedExercisesTimestamp';
    const MAX_CACHE_AGE = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

    useEffect(() => {
        loadCachedExercises();
    }, []);

    // Debounced fetch function to prevent multiple rapid API calls
    const debouncedFetchExercises = useCallback(
        debounce((query) => {
            fetchExercises(query);
        }, 300),
        [authToken] // Ensure debounce updates when authToken changes
    );

    useEffect(() => {
        // Trigger debounced search whenever searchQuery changes
        debouncedFetchExercises(searchQuery);
    }, [searchQuery, debouncedFetchExercises]);

    /**
     * Load exercises from AsyncStorage
     */
    const loadCachedExercises = async () => {
        try {
            const [cachedData, cachedTimestamp] = await Promise.all([
                AsyncStorage.getItem(CACHE_KEY),
                AsyncStorage.getItem(CACHE_TIMESTAMP_KEY),
            ]);

            if (cachedData !== null && cachedTimestamp !== null) {
                const parsedData = JSON.parse(cachedData);
                const timestamp = parseInt(cachedTimestamp, 10);
                const currentTime = Date.now();
                const cacheAge = currentTime - timestamp;

                if (cacheAge < MAX_CACHE_AGE) {
                    setExercises(parsedData);
                    console.log('Loaded exercises from cache.');
                    setLoading(false);
                    return;
                } else {
                    console.log('Cache is stale. Fetching fresh data.');
                }
            } else {
                console.log('No cached data found. Fetching from API.');
            }

            // Fetch fresh data
            fetchExercises();
        } catch (error) {
            console.error('Error loading cached exercises:', error);
            Alert.alert('Error', 'Failed to load cached exercises.');
            fetchExercises();
        }
    };

    /**
     * Fetch exercises from the API
     * @param {string} query - Search query
     */
    const fetchExercises = async (query = '') => {
        if (!authToken) {
            Alert.alert('Authentication Error', 'Please log in to fetch exercises.');
            setLoading(false);
            return;
        }

        console.log('Fetching exercises with token:', authToken);

        try {
            const response = await axios.get('http://10.0.0.203:5000/api/exercises', {
                headers: {
                    Authorization: `Bearer ${authToken}`,
                },
                params: {
                    search: query,
                    limit: 50, // Adjust as needed
                },
            });

            if (response.status === 200) {
                const fetchedExercises = response.data;
                setExercises(fetchedExercises);

                // Cache the fetched data with a timestamp
                await Promise.all([
                    AsyncStorage.setItem(CACHE_KEY, JSON.stringify(fetchedExercises)),
                    AsyncStorage.setItem(CACHE_TIMESTAMP_KEY, Date.now().toString()),
                ]);
                console.log('Fetched exercises from API and cached.');
            } else {
                console.error('Unexpected response status:', response.status);
                Alert.alert('Error', 'Unexpected response from the server.');
            }
        } catch (error) {
            console.error('Error fetching exercises:', error.response ? error.response.data : error.message);
            Alert.alert('Error', 'Failed to fetch exercises from the server.');
        } finally {
            setLoading(false);
            setIsRefreshing(false);
        }
    };

    /**
     * Handle user input in the search bar
     * @param {string} text - Search query text
     */
    const handleSearch = (text) => {
        setSearchQuery(text);
    };

    /**
     * Handle pull-to-refresh action
     */
    const onRefresh = () => {
        setIsRefreshing(true);
        fetchExercises(searchQuery);
    };

    /**
     * Clear cached data manually
     */
    const clearCache = async () => {
        try {
            await AsyncStorage.multiRemove([CACHE_KEY, CACHE_TIMESTAMP_KEY]);
            setExercises([]);
            Alert.alert('Success', 'Cache has been cleared.');
        } catch (error) {
            console.error('Error clearing cache:', error);
            Alert.alert('Error', 'Failed to clear cache.');
        }
    };

    /**
     * Render each exercise item
     * @param {object} item - Exercise object
     */
    const renderItem = ({ item }) => (
        <View style={styles.itemContainer}>
            {item.imageUrl ? (
                <Image source={{ uri: item.imageUrl }} style={styles.image} resizeMode="cover" />
            ) : (
                <View style={[styles.image, styles.imagePlaceholder]}>
                    <Text style={styles.imagePlaceholderText}>No Image</Text>
                </View>
            )}
            <Text style={styles.title}>{item.name}</Text>
            {item.description ? <Text style={styles.description}>{item.description}</Text> : null}
            {item.videoUrl ? (
                <TouchableOpacity onPress={() => Linking.openURL(item.videoUrl)}>
                    <Text style={styles.link}>Video Tutorial</Text>
                </TouchableOpacity>
            ) : null}
        </View>
    );

    if (loading && exercises.length === 0) {
        return (
            <View style={styles.loader}>
                <ActivityIndicator size="large" color="#0000ff" />
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <TextInput
                    style={styles.searchBar}
                    placeholder="Search exercises..."
                    value={searchQuery}
                    onChangeText={handleSearch}
                    autoCapitalize="none"
                    autoCorrect={false}
                    clearButtonMode="while-editing"
                />
                <TouchableOpacity style={styles.clearCacheButton} onPress={clearCache}>
                    <Text style={styles.clearCacheButtonText}>Clear Cache</Text>
                </TouchableOpacity>
            </View>
            <FlatList
                data={exercises}
                keyExtractor={(item, index) => `${item.name}-${index}`}
                renderItem={renderItem}
                contentContainerStyle={styles.list}
                keyboardShouldPersistTaps="handled"
                refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} />}
                ListEmptyComponent={
                    !loading && (
                        <View style={styles.emptyContainer}>
                            <Text style={styles.emptyText}>No exercises found.</Text>
                        </View>
                    )
                }
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        paddingTop: 10,
        paddingBottom: 5,
    },
    searchBar: {
        flex: 1,
        height: 50,
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 8,
        marginRight: 10,
        paddingHorizontal: 15,
        fontSize: 16,
    },
    clearCacheButton: {
        height: 50,
        backgroundColor: '#ff4d4d',
        borderRadius: 8,
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 15,
    },
    clearCacheButtonText: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold',
    },
    itemContainer: {
        padding: 10,
        borderBottomWidth: 1,
        borderColor: '#ccc',
    },
    image: {
        width: '100%',
        height: 200,
        marginBottom: 10,
        borderRadius: 10,
    },
    imagePlaceholder: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#e0e0e0',
    },
    imagePlaceholderText: {
        color: '#555',
    },
    title: {
        fontSize: 18,
        fontWeight: 'bold',
    },
    description: {
        marginTop: 5,
        fontSize: 14,
        color: '#555',
    },
    link: {
        color: 'blue',
        marginTop: 5,
    },
    loader: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    list: {
        paddingBottom: 20,
    },
    emptyContainer: {
        flex: 1,
        alignItems: 'center',
        marginTop: 50,
    },
    emptyText: {
        fontSize: 16,
        color: '#555',
    },
});

export default ExercisesScreen;