import React, {
  useState,
  useCallback,
  useEffect,
  setGlobal,
  useGlobal,
} from "reactn";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { useFonts } from "expo-font";
import * as SplashScreen from "expo-splash-screen";
import { StatusBar } from "expo-status-bar";
import { NavigationContainer, DefaultTheme } from "@react-navigation/native";
import moment from "moment";
import "moment/locale/fr";
import "@expo/metro-runtime";
import { PortalProvider } from "@gorhom/portal";

import { MainStack, Routes } from "./src/navigation";
import { Palette } from "./src/styles";

import { navigationRef, reset } from "./src/navigation/NavigationService";

import initialGlobalState from "./src/config/initialGlobalState";
import { MenuProvider } from "react-native-popup-menu";

import firebase from "./src/config/firebase";
import Providers from "./src/providers";
import AppLayout from "./src/layouts/AppLayout";
import {
  Inter_400Regular,
  Inter_400Regular_Italic,
  Inter_500Medium,
  Inter_600SemiBold,
  Inter_700Bold,
} from "@expo-google-fonts/inter";

import "./src/utils/Sheet";
import {LogBox} from "react-native";
import CommentsBottomSheet from "./src/components/bottomsheets/CommentsBottomSheet";

console.disableYellowBox = true;
console.reportErrorsAsExceptions = false;

moment.locale("fr");

setGlobal(initialGlobalState);

SplashScreen.preventAutoHideAsync();

const App = () => {
  const [currentUID, setCurrentUID] = useGlobal("currentUID");
  const [, setCurrentUserRoles] = useGlobal("currentUserRoles");

  const [appIsReady, setAppIsReady] = useState(false);

  const [isInitializing, setInitializing] = useState(true);

  const [loaded] = useFonts({
    NewYorkSemibold: require("./src/assets/fonts/NewYork-Semibold.ttf"),
    OpenSansRegular: require("./src/assets/fonts/OpenSans-Regular.ttf"),
    InterRegular: Inter_400Regular,
    InterMedium: Inter_500Medium,
    InterSemiBold: Inter_600SemiBold,
    InterBold: Inter_700Bold,
    InterRegularItalic: Inter_400Regular_Italic,
    HelveticaNeueRegular: require("./src/assets/fonts/HelveticaNeueRegular.ttf"),
    HelveticaNeueMedium: require("./src/assets/fonts/HelveticaNeueMedium.ttf"),
    HelveticaNeueBold: require("./src/assets/fonts/HelveticaNeueBold.ttf"),
    OwnersRegular: require("./src/assets/fonts/OwnersRegular.ttf"),
    OwnersMedium: require("./src/assets/fonts/OwnersMedium.ttf"),
    OwnersBold: require("./src/assets/fonts/OwnersBold.ttf"),
  });

  useEffect(() => {
    if (loaded) {
      setAppIsReady(true);
      LogBox.ignoreAllLogs();
    }
  }, [loaded]);

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

  useEffect(() => {
    const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  }, []);

  const onAuthStateChanged = async (user) => {
    if (isInitializing) {
      setInitializing(false);
    }

    if (user?.uid) {
      setCurrentUID(user.uid);

      const idTokenResult = await user.getIdTokenResult();
      setCurrentUserRoles(idTokenResult?.claims?.roles || []);
    } else {
      setCurrentUID(null);
      setGlobal(initialGlobalState);
      reset({
        index: 0,
        routes: [{ name: Routes.Splash }],
      });
    }
  };

  if (!loaded || isInitializing) {
    return null;
  }

  return (
    <>
      <StatusBar style="light" />

      <GestureHandlerRootView
        onLayout={onLayoutRootView}
        style={[{ flex: 1, backgroundColor: Palette.darkPurple }]}
      >
        <PortalProvider>
          <Providers>
            <MenuProvider>
              <AppLayout currentUID={currentUID}>
                <NavigationContainer
                  theme={{
                    ...DefaultTheme,
                    colors: {
                      ...DefaultTheme.colors,
                      background: Palette.darkPurple,
                    },
                  }}
                  ref={navigationRef}
                  documentTitle={{
                    formatter: (options) =>
                      options?.title
                        ? `${options?.title} - minuit.starter`
                        : "minuit.starter",
                  }}
                >
                  <MainStack />
                </NavigationContainer>
                <CommentsBottomSheet />
              </AppLayout>
            </MenuProvider>
          </Providers>
        </PortalProvider>
      </GestureHandlerRootView>
    </>
  );
};

export default App;
