import React, { useEffect, useRef, useState } from 'react';
import { Alert, LogBox, SafeAreaView, StatusBar } from 'react-native';
import 'react-native-gesture-handler';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Atlas from './src/components/Atlas';
import 'expo-asset';
import AppLoading from 'expo-app-loading';
import * as Updates from "expo-updates";
import { Asset } from 'expo-asset';
import { MenuProvider } from 'react-native-popup-menu';
import { createNavigationContainerRef, NavigationContainer } from '@react-navigation/native';
import { colors } from './src/utils/GlobalUtils';
import { AuthContextProvider } from './src/data/Auth/AuthContext';
import { QueryClient, QueryClientProvider, useQueryClient } from 'react-query';

const App: React.FC = () => {
  const updateDismissed = useRef<boolean>(false)

  const queryClient = new QueryClient()

  useEffect(() => {
    if (!__DEV__) {
      const timer = setInterval(async () => {
        const update = await Updates.checkForUpdateAsync()
        if (update.isAvailable && !updateDismissed.current) {
          updateDismissed.current = true
          setTimeout(() => {
            Alert.alert('Update Available', 'An update is available. Would you like to update now?', [
              {"text": "Yes", "onPress": async () => {
                await Updates.fetchUpdateAsync()
                await Updates.reloadAsync()
              }},
              {"text": "No", "onPress": () => {
                Alert.alert('Update Available', 'Update dismissed, you can always revisit it in settings', [
                  {"text": "OK"}
                ])
              }}
            ])
          }, 1000);
        }
    }, 5000)
    return () => clearInterval(timer)
  }}, [])

  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();
    }); 

    Promise.all(cacheImages);
  }

  if (loading) {
    return (
      <AppLoading
        startAsync={_cacheResourcesAsync}
        onFinish={() => setLoading(false)}
        onError={console.warn}
      />
    ); 
  }
  return (
    <SafeAreaProvider>
      <QueryClientProvider client={queryClient}>
        <MenuProvider>
          <SafeAreaView style={{height: '100%', backgroundColor: colors.red}}>
            <StatusBar barStyle='light-content' backgroundColor={colors.red}/>
            <NavigationContainer>
              <AuthContextProvider>
                <Atlas/>
              </AuthContextProvider>
            </NavigationContainer>  
          </SafeAreaView>
        </MenuProvider>
      </QueryClientProvider>
    </SafeAreaProvider>
  );
}

export default App;