import {createAppContainer} from 'react-navigation';
import {Provider} from 'react-redux';
import React, {Component} from 'react';
import {View, StatusBar, SafeAreaView, Platform} from 'react-native';
import SplashScreen from 'react-native-splash-screen';
import FlashMessage from 'react-native-flash-message';
import messaging from '@react-native-firebase/messaging';
import {authSetPushNotificationToken} from './shared/actions/auth';

import NavigationService from './shared/services/NavigationService';

import AppNavigator from './screens/AppNavigator';

import store from './store';
import * as Sentry from '@sentry/react-native';

Sentry.init({
  dsn: 'https://88838300cc944514a5034f7f5f984993@o407546.ingest.sentry.io/6162880',
  // Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring.
  // We recommend adjusting this value in production.
  tracesSampleRate: 1.0,
});

const AppContainer = createAppContainer(AppNavigator);

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight;
const HEADER_HEIGHT = Platform.OS === 'ios' ? 32 : 16;

class Root extends Component {
  state = {
    openedByNotificationAndShouldRedirect: false,
  };

  async componentDidMount() {
    SplashScreen.hide();
    this.onTokenRefreshListener = messaging().onTokenRefresh(
      (pushNotificationToken) => {
        this.updateToken(pushNotificationToken);
      }
    );

    this.notificationOpenedListener = messaging().onNotificationOpenedApp(
      (notificationOpen) => {
        const {data} = notificationOpen.notification;
        NavigationService.navigate('messagesStack');
      }
    );

    const openedByNotification = await messaging().getInitialNotification();
    if (openedByNotification) {
      NavigationService.navigate('messagesStack');
    }
  }

  async updateToken(pushNotificationToken) {
    if (!pushNotificationToken) {
      pushNotificationToken = await messaging().getToken();
    }
    if (!pushNotificationToken) {
      return;
    }

    store.dispatch(authSetPushNotificationToken(pushNotificationToken));
  }

  componentWillUnmount() {
    this.onTokenRefreshListener();
    this.notificationOpenedListener();
  }

  render() {
    return (
      <Provider store={store}>
        <View style={{height: STATUS_BAR_HEIGHT, backgroundColor: '#006ca5'}}>
          <StatusBar
            translucent
            backgroundColor="#006ca5"
            barStyle="light-content"
          />
        </View>
        <View style={{backgroundColor: '#006ca5', height: HEADER_HEIGHT}} />
        <SafeAreaView style={{flex: 1}}>
          <AppContainer
            ref={(navigatorRef) =>
              NavigationService.setTopLevelNavigator(
                navigatorRef ? navigatorRef._navigation : null
              )
            }
          />
          <FlashMessage position="top" />
        </SafeAreaView>
      </Provider>
    );
  }
}

export default Sentry.wrap(Root);
