import i18next, { getLanguage } from "../services/i18n/index";
import FontAwesome from "@expo/vector-icons/FontAwesome";
import { useFonts } from "expo-font";
import { Stack, useRouter } from "expo-router";
import * as SplashScreen from "expo-splash-screen";
import { useEffect, useState } from "react";
import "react-native-reanimated";
import { I18nextProvider } from "react-i18next";

import { useColorScheme } from "@/components/useColorScheme";

export { ErrorBoundary } from "expo-router";

export const unstable_settings = {
  initialRouteName: "(tabs)",
};

SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [loaded, error] = useFonts({
    SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"),
    ...FontAwesome.font,
  });

  const [appIsReady, setAppIsReady] = useState(false);
  const [shouldRedirect, setShouldRedirect] = useState(false);
  const router = useRouter();

  useEffect(() => {
    const initLang = async () => {
      const lang = await getLanguage();
      if (!lang) {
        console.log("Redirecting to language init...");
        setShouldRedirect(true);
      }

      setAppIsReady(true);
    };

    initLang();
  }, []);

  useEffect(() => {
    if (error) throw error;
  }, [error]);

  useEffect(() => {
    if (loaded && appIsReady) {
      SplashScreen.hideAsync();
    }
  }, [loaded, appIsReady]);

  useEffect(() => {
    if (appIsReady && shouldRedirect) {
      router.replace("/init/language");
      setShouldRedirect(false);
    }
  }, [appIsReady, shouldRedirect]);

  if (!loaded || !appIsReady) {
    console.log("!loaded || !appIsReady", loaded, appIsReady);
    return null;
  }

  return <RootLayoutNav />;
}

function RootLayoutNav() {
  return (
    <I18nextProvider i18n={i18next}>
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="modal" options={{ presentation: "modal" }} />
      </Stack>
    </I18nextProvider>
  );
}
