import React, {useEffect} from 'react';
import {View, Text, ImageBackground, StyleSheet, StatusBar} from 'react-native';

import {connect} from 'react-redux';
import StackNavigation from './routers/StackNavigation';
import Modal from 'react-native-modal';
import {SkypeIndicator} from 'react-native-indicators';
import {HEIGHT, HEIGHTXD} from './Config/Functions';
import R from './assets/R';
import FirebaseNotification from './helper/FirebaseNotification';
import messaging from '@react-native-firebase/messaging';
import {enableScreens} from 'react-native-screens';
import AsyncStorage from '@react-native-community/async-storage';
import KEY from './assets/AsynStorage';
import firebase from '@react-native-firebase/app';
enableScreens();

const RootView = (props) => {
  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('Message handled in the background!', remoteMessage);
  });
  useEffect(() => {
    requestUserPermission();
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      console.log('A new FCM message arrived!', remoteMessage);
    });
    return unsubscribe;
  }, []);

  const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      getFcmToken();
      console.log('Authorization status:', authStatus);
    }
  };
  const getFcmToken = async () => {
    let fcmToken = await AsyncStorage.getItem(KEY.FIREBASE);
    console.log('Dat tao', fcmToken);
    if (!fcmToken) {
      fcmToken = await messaging().getToken();
      console.log('Vua tao', fcmToken);
      if (fcmToken) {
        AsyncStorage.setItem(KEY.FIREBASE, fcmToken);
      }
    }
  };

  onReceived = (notification) => {};
  onOpened = (notification) => {
    console.log(('notification', notification));
  };
  return (
    <View style={{flex: 1}}>
      {/*<FirebaseNotification onReceived={onReceived} onOpened={onOpened} />*/}
      <Modal isVisible={props.loadingModal.isVisible}>
        <SkypeIndicator color={'white'} />
      </Modal>
      <StackNavigation />
    </View>
  );
};

const mapStateToProps = (state) => {
  return {
    loadingModal: state.ModalLoadingReducer,
  };
};

export default connect(mapStateToProps, {})(RootView);
