/* eslint-disable no-console */
import React, {useEffect} from 'react';
import {Platform, View, Alert} from 'react-native';
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-community/async-storage';
import KEY from '../assets/AsynStorage';
import {showNotificaton, updateNotification} from '../actions/SnackBarAction';
import {connect} from 'react-redux';
const FirebaseNotification = (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);
      props.showNotificaton({
        title: 'Title',
        content: 'Content notification',
        screen: 'NOTIFICATION',
        id_record: 9,
      });
    });
    return unsubscribe;
  }, []);

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

    if (enabled) {
      getFcmToken();
    }
  };
  const getFcmToken = async () => {
    let fcmToken = await AsyncStorage.getItem(KEY.FIREBASE);
    if (!fcmToken) {
      fcmToken = await messaging().getToken();
      if (fcmToken) {
        AsyncStorage.setItem(KEY.FIREBASE, fcmToken);
      }
    }
  };
  return <View />;
};

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

export default connect(mapStateToProps, {showNotificaton, updateNotification})(
  FirebaseNotification,
);
