import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';
import 'react-native-reanimated';
import { useColorScheme } from 'react-native';
import { PaperProvider, Provider } from "react-native-paper";
import { UserProvider, useUser } from "@/context/UserContext";
import themes from '@/assets/themes'
import log from "@/util/log"

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
    return (
        <UserProvider>
            <InnerRootLayout />
        </UserProvider>
    );
}

function InnerRootLayout() {
    const { currentTheme } = useUser(); // Access the currentTheme from UserContext
    log.debug(currentTheme);
    const colorScheme = useColorScheme();
    log.debug(colorScheme);
    const [loaded] = useFonts({
        SpaceReg: require('../assets/fonts/SpaceMono-Regular.ttf'),
        SpaceBold: require('../assets/fonts/SpaceMono-Bold.ttf'),
        Light: require('../assets/fonts/font-light.otf'),
        Medium: require('../assets/fonts/font-medium.otf'),
        Heavy: require('../assets/fonts/font-heavy.otf'),
    });
    useEffect(() => {
        if (loaded) {
            SplashScreen.hideAsync();
        }
    }, [loaded]);

    if (!loaded) {
        return null;
    }

    // Ensure currentTheme is treated as a valid key, or fallback to 'blue'
    //const themeKey: 'blue' | 'green' | 'red' | 'yellow' | 'orange' = (currentTheme as 'blue' | 'green' | 'red' | 'yellow' | 'orange') || 'blue';

    // Use the themeKey to index into the themes object

    //const appTheme = themes[themeKey][colorScheme === 'dark' ? 'dark' : 'light'];
    const appTheme = themes[currentTheme as keyof typeof themes][colorScheme === 'dark' ? 'dark' : 'light']

    return (
        <Provider>
            <PaperProvider theme={appTheme}>
                <Stack>
                    <Stack.Screen name="index" options={{ headerShown: false }} />
                </Stack>
            </PaperProvider>
        </Provider>
    );
}
