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, useState } from 'react';
import { setupInterceptors } from 'src/utils/request';
import { ErrorModal, WarningModal } from 'src/components';
import { NotificationProvider } from 'src/contexts/NotificationContext';
import React from 'react';
import { Linking, Platform } from 'react-native';
import { API_URL, APP_VERSION } from 'src/constants';
import axios from 'axios';
import { API } from 'src/types';

const IOS_STORE_URL = 'https://apps.apple.com/app/id6502843543';
const ANDROID_STORE_URL =
  'https://play.google.com/store/apps/details?id=com.nomadmania.presentation';

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

Sentry.init({
  dsn: 'https://c9b37005f4be22a17a582603ebc17598@o4507781200543744.ingest.de.sentry.io/4507781253824592',
  integrations: [Sentry.reactNativeTracingIntegration({ 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);
  const [isUpdateAvailable, setIsUpdateAvailable] = useState(false);

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

  useEffect(() => {
    const checkLatestVersion = async () => {
      try {
        const response = await axios.get(API_URL + '/' + API.LATEST_VERSION, {
          headers: {
            'App-Version': APP_VERSION,
            Platform: Platform.OS
          }
        });
        const { version } = response.data;

        if (APP_VERSION !== version) {
          setIsUpdateAvailable(true);
        }
      } catch (error) {
        console.error('Failed to check latest version:', error);
      }
    };

    checkLatestVersion();
  }, []);

  const handleUpdatePress = () => {
    const storeUrl = Platform.OS === 'ios' ? IOS_STORE_URL : ANDROID_STORE_URL;
    Linking.openURL(storeUrl).catch((err) => console.error('Failed to open store URL:', err));
  };

  return (
    <ConnectionProvider>
      <RegionProvider>
        <NavigationContainer
          ref={navigation}
          onReady={() => {
            routingInstrumentation.registerNavigationContainer(navigation);
          }}
        >
          <Route />
          <ConnectionBanner />
          <ErrorModal />
          <WarningModal
            isVisible={isUpdateAvailable}
            type="success"
            title="Update Available"
            message="A new version of the NomadMania app is available. Please update to the latest version."
            action={handleUpdatePress}
            onClose={() => setIsUpdateAvailable(false)}
          />
        </NavigationContainer>
      </RegionProvider>
    </ConnectionProvider>
  );
};

export default Sentry.wrap(App);
