import 'react-native-gesture-handler';
import 'expo-splash-screen';
import { QueryClientProvider } from '@tanstack/react-query';
import { NavigationContainer } from '@react-navigation/native';
import { queryClient } from 'src/utils/queryClient';
import * as Sentry from '@sentry/react-native';

import Route from './Route';
import { ConnectionProvider } from 'src/contexts/ConnectionContext';
import ConnectionBanner from 'src/components/ConnectionBanner/ConnectionBanner';
import { RegionProvider } from 'src/contexts/RegionContext';
import { ErrorProvider, useError } from 'src/contexts/ErrorContext';
import { useEffect } from 'react';
import { setupInterceptors } from 'src/utils/request';
import { ErrorModal } from 'src/components';
import { NotificationProvider } from 'src/contexts/NotificationContext';
import React from 'react';

const routingInstrumentation = new Sentry.ReactNavigationInstrumentation({
  enableTimeToInitialDisplay: true
});

Sentry.init({
  dsn: 'https://c9b37005f4be22a17a582603ebc17598@o4507781200543744.ingest.de.sentry.io/4507781253824592',
  integrations: [new Sentry.ReactNativeTracing({ routingInstrumentation })],
  debug: false,
  ignoreErrors: ['Network Error', 'ECONNABORTED', 'timeout of 10000ms exceeded'],
});

const App = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <NotificationProvider>
        <ErrorProvider>
          <InnerApp />
        </ErrorProvider>
      </NotificationProvider>
    </QueryClientProvider>
  );
};

const InnerApp = () => {
  const errorContext = useError();
  const navigation = React.useRef(null);

  useEffect(() => {
    setupInterceptors(errorContext);
  }, [errorContext]);

  return (
    <ConnectionProvider>
      <RegionProvider>
        <NavigationContainer
          ref={navigation}
          onReady={() => {
            routingInstrumentation.registerNavigationContainer(navigation);
          }}
        >
          <Route />
          <ConnectionBanner />
          <ErrorModal />
        </NavigationContainer>
      </RegionProvider>
    </ConnectionProvider>
  );
};

export default Sentry.wrap(App);
