import 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { QueryClientProvider } from 'react-query';
import Navigation from './src/navigation';
import { NativeBaseProvider } from 'native-base';
import queryClient from './src/services/queryclient';
import { extendedTheme } from './src/theme';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect, useState } from 'react';
import { useGetHeatPumpConfig, useGetHeatPumpState } from './src/queries/heatpump';
import api from './src/services/api';
import { FontAwesome, FontAwesome5, Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import * as Font from 'expo-font';

SplashScreen.preventAutoHideAsync();

export default function App() {
  const [isPreloadComplete, setIsPreloadComplete] = useState(false);

  useEffect(() => {
    // preload data and fonts to avoid flickering
    const preload = async () => {
      try {
        await queryClient.fetchQuery({
          queryKey: useGetHeatPumpConfig.key,
          queryFn: api.HeatPumpApi.getConfig,
          retry: false,
        });
        await queryClient.fetchQuery({
          queryKey: useGetHeatPumpState.key,
          queryFn: api.HeatPumpApi.getState,
          retry: false,
        });
        await Font.loadAsync({
          ...FontAwesome.font,
          ...FontAwesome5.font,
          ...Ionicons.font,
          ...MaterialCommunityIcons.font,
        });
      } catch (e) {
        // could not fetch data (server is not available)
        setTimeout(SplashScreen.hideAsync, 1000);
      } finally {
        setIsPreloadComplete(true);
      }
    };
    preload();
  }, []);

  return (
    <NativeBaseProvider theme={extendedTheme}>
      <QueryClientProvider client={queryClient}>
        <SafeAreaProvider>
          <StatusBar />
          {isPreloadComplete && <Navigation />}
        </SafeAreaProvider>
      </QueryClientProvider>
    </NativeBaseProvider>
  );
}
