// Import  global CSS file
import '../../global.css';

import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
import { ThemeProvider } from '@react-navigation/native';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import React, { useCallback, useEffect, useState } from 'react';
import { StyleSheet } from 'react-native';
import FlashMessage from 'react-native-flash-message';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { KeyboardProvider } from 'react-native-keyboard-controller';
import * as Font from 'expo-font';

import { APIProvider } from '@/api';
import { hydrateAuth, loadSelectedTheme } from '@/lib';
// import { useThemeConfig } from '@/lib/use-theme-config';
import { PaperProvider } from 'react-native-paper';

export { ErrorBoundary } from 'expo-router';

export const unstable_settings = {
  initialRouteName: '(app)',
};

hydrateAuth();
loadSelectedTheme();

export default function RootLayout() {
  const [fontsLoaded, setFontsLoaded] = useState(false);

  const loadFonts = async () => {
    await Font.loadAsync({
      pretendard100: require('../../assets/fonts/Pretendard-Thin.otf'),
      pretendard200: require('../../assets/fonts/Pretendard-ExtraLight.otf'),
      pretendard300: require('../../assets/fonts/Pretendard-Light.otf'),
      pretendard400: require('../../assets/fonts/Pretendard-Regular.otf'),
      pretendard500: require('../../assets/fonts/Pretendard-Medium.otf'),
      pretendard600: require('../../assets/fonts/Pretendard-SemiBold.otf'),
      pretendard700: require('../../assets/fonts/Pretendard-Bold.otf'),
      pretendard800: require('../../assets/fonts/Pretendard-ExtraBold.otf'),
      pretendard900: require('../../assets/fonts/Pretendard-Black.otf'),
      Inter: require('../../assets/fonts/Inter.ttf'),
    });
    setFontsLoaded(true);
  };

  useEffect(() => {
    const prepare = async () => {
      try {
        await SplashScreen.preventAutoHideAsync();
        await loadFonts();
      } catch (e) {
        console.warn(e);
      } finally {
        console.log('prepare =====');
        setFontsLoaded(true);
      }
    };

    prepare();
  }, []);

  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded) {
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded]);

  if (!fontsLoaded) {
    return null; // 스플래시 화면이 유지됩니다.
  }

  return (
    <Providers>
      <GestureHandlerRootView
        style={styles.container}
        onLayout={onLayoutRootView}
      >
        <Stack>
          <Stack.Screen name="(app)" options={{ headerShown: false }} />
          <Stack.Screen name="onboarding" options={{ headerShown: false }} />
          <Stack.Screen name="login" options={{ headerShown: false }} />
        </Stack>
      </GestureHandlerRootView>
    </Providers>
  );
}

function Providers({ children }: { children: React.ReactNode }) {
  // const theme = useThemeConfig();
  return (
    <GestureHandlerRootView style={styles.container}>
      <KeyboardProvider>
        <APIProvider>
          <PaperProvider>
            <BottomSheetModalProvider>
              {children}
              <FlashMessage position="bottom" />
            </BottomSheetModalProvider>
          </PaperProvider>
        </APIProvider>
      </KeyboardProvider>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
