Make the exercise screen use the theme set in the app.js
// 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 * as SecureStore from 'expo-secure-store';

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();
    }, [authToken]); // Reload when token changes

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

    useEffect(() => {
        // Trigger debounced search whenever searchQuery changes
        if (searchQuery.length === 0 || searchQuery.length > 2) { // Trigger search after 3 characters
            debouncedFetchExercises(searchQuery);
        }
    }, [searchQuery, debouncedFetchExercises]);

    /**
     * Load exercises from SecureStore
     */
    const loadCachedExercises = async () => {
        if (!authToken) {
            setLoading(false);
            return;
        }

        try {
            const [cachedData, cachedTimestamp] = await Promise.all([
                SecureStore.getItemAsync(CACHE_KEY),
                SecureStore.getItemAsync(CACHE_TIMESTAMP_KEY),
            ]);

            if (cachedData && cachedTimestamp) {
                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 SecureStore.');
                    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,
                },
            });

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

                // Cache the fetched data with a timestamp
                await Promise.all([
                    SecureStore.setItemAsync(CACHE_KEY, JSON.stringify(fetchedExercises)),
                    SecureStore.setItemAsync(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 SecureStore.deleteItemAsync(CACHE_KEY);
            await SecureStore.deleteItemAsync(CACHE_TIMESTAMP_KEY);
            setExercises([]);
            console.log('Cache cleared successfully.');
            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._id ? item._id : index.toString()} // Fallback to index if _id is missing
                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;

// App.js
import React from 'react';
import { AuthProvider } from './context/AuthContext';
import AppNavigator from './navigation/AppNavigator';
import { Provider as PaperProvider, DarkTheme as PaperDarkTheme } from 'react-native-paper';
import { StatusBar } from 'expo-status-bar';
import { NavigationContainer, DarkTheme as NavigationDarkTheme } from '@react-navigation/native';
import merge from 'deepmerge';

// Merge react-native-paper's DarkTheme with react-navigation's DarkTheme
const CombinedDarkTheme = merge(PaperDarkTheme, NavigationDarkTheme);

// Customize the merged theme with your specific color preferences
const customDarkTheme = {
    ...CombinedDarkTheme,
    dark: true, // Ensure dark mode is explicitly set
    colors: {
      ...CombinedDarkTheme.colors,
      primary: '#2196F3',
      accent: '#03dac6',
      background: '#121212',
      surface: '#1e1e1e',
      text: '#ffffff',
      placeholder: '#cccccc',
      error: '#cf6679',
      // Add other necessary color properties
      onSurface: '#ffffff',
      disabled: '#3e3e3e',
      backdrop: '#000000',
      // Ensure all required color properties are defined
    },
  };

const App = () => {
  return (
    <AuthProvider>
      <PaperProvider theme={customDarkTheme}>
        <StatusBar style="light" />
        <NavigationContainer theme={customDarkTheme}>
          <AppNavigator />
        </NavigationContainer>
      </PaperProvider>
    </AuthProvider>
  );
};

export default App;