import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { LogBox, StatusBar, Text } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Asset } from 'expo-asset';
import AppLoading from 'expo-app-loading';
import { QueryClient, QueryClientProvider } from 'react-query';
import {createNavigationContainerRef, NavigationContainer,} from '@react-navigation/native'
import AuthStateProvider from './src/libs/auth/AuthStateProvider'
import { LoadingScreen } from './src/components/LoadingScreen';
import AuthorizedNavigator from './src/navigation/AuthorizedNavigator';
import UnauthorizedNavigator from './src/navigation/UnauthorizedNavigator';
import { MenuProvider } from 'react-native-popup-menu';
import { colors } from './src/utils/GlobalUtils';
import { observer } from 'mobx-react';

const App = () => {
  const navigationRef = createNavigationContainerRef()

  LogBox.ignoreAllLogs();
  const [loading, setLoading] = useState(false);
  const _cacheResourcesAsync = async () => {
    const images = [
      require('./assets/logo-white.png'),
      require('./assets/cover-dark.png'),
      require('./assets/cover.jpg'),
      require('./assets/default-pfp.png'),
      require('./assets/pothole.png'),
      require('./assets/roadblock.png'),
      require('./assets/barrier.png'),
      require('./assets/bump.png'),
      require('./assets/information.png'),
      require('./assets/washroom.png'),
      require('./assets/park.png'),
    ];

    const cacheImages = images.map(image => {
      return Asset.fromModule(image).downloadAsync();
    }); 

    await Promise.all(cacheImages);
  }

  const queryClient = new QueryClient()

  if (loading) {
    return (
      <AppLoading
        startAsync={_cacheResourcesAsync}
        onFinish={() => setLoading(false)}
        onError={console.warn}
      />
    ); 
  }

  return (
    <NavigationContainer ref={navigationRef}>  
      <MenuProvider>
        <SafeAreaProvider>
          <QueryClientProvider client={queryClient}>
          <StatusBar barStyle='light-content' backgroundColor={colors.red}/>
          {/* <AuthStateProvider authenticatedView={<AuthorizedNavigator/>} unauthenticatedView={<UnauthorizedNavigator/>}/>      */}
          <AuthStateProvider>
              {(authenticated, checkingState) => 
                <>
                  <StatusBar barStyle='light-content' backgroundColor={colors.red}/>
                  {checkingState ? 
                    <LoadingScreen/> : 
                    <>
                      {authenticated ? 
                        <AuthorizedNavigator  /> : 
                        <UnauthorizedNavigator /> }
                    </>}
                </>
              }         
            </AuthStateProvider>
          </QueryClientProvider>
        </SafeAreaProvider>
      </MenuProvider>
    </NavigationContainer> 
  );
}

export default observer(App)