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 { themes } from '@/app/themes'
import { UserProvider, useUser } from "@/context/UserContext";

// 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
  console.log(currentTheme);
  const colorScheme = useColorScheme();
  console.log(colorScheme);
  const [loaded] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });
  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'];


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