/* eslint-disable no-console */
import React from 'react';
import {Platform, View, Alert} from 'react-native';
import firebase from '@react-native-firebase/app';
import sampleaudio from '../../sampleaudio.mp3';
import AsyncStorage from '@react-native-community/async-storage';
import KEY from '../assets/AsynStorage';

class FirebaseNotification extends React.PureComponent {
  checkPermission = () => {
    firebase
      .messaging()
      .hasPermission()
      .then((enabled) => {
        if (enabled) {
          this.getToken();
        } else {
          this.requestPermission();
        }
      });
  };

  requestPermission = async () => {
    try {
      await firebase.messaging().requestPermission();
      this.getToken();
    } catch (error) {}
  };

  getToken = async () => {
    let fcmToken = await AsyncStorage.getItem(KEY.FIREBASE);
    console.log('Dat tao', fcmToken);
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      console.log('Vua tao', fcmToken);
      if (fcmToken) {
        AsyncStorage.setItem(KEY.FIREBASE, fcmToken);
      }
    }
  };

  async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
    this.removeNotificationDisplayedListener = firebase
      .notifications()
      .onNotificationDisplayed((notification) => {
        console.log('Can alert', notification);

        this.props.onReceived(notification);

        // Process your notification as required
        // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
      });
  }

  componentWillUnmount() {
    this.removeNotificationDisplayedListener;
    this.notificationListener;
    this.notificationOpenedListener;
  }

  async createNotificationListeners() {
    /*
     * Triggered when a particular notification has been received in foreground
     * */
    console.log('Notification log');
    const channel = new firebase.notifications.Android.Channel(
      '500',
      'Channel Name 1001',
      firebase.notifications.Android.Importance.Max,
    )
      .setDescription('A natural description of the channel')
      .setSound('default');

    firebase.notifications().android.createChannel(channel);
    this.notificationListener = firebase
      .notifications()
      .onNotification((notification) => {
        console.log('notificaiton', notification);
        if (Platform.OS === 'android') {
          const localNotification = new firebase.notifications.Notification({
            sound: sampleaudio,
            show_in_foreground: true,
          })
            .setSound('default')
            .setNotificationId(notification.notificationId)
            .setTitle(notification.title)
            .setBody(notification.body)
            .setData(notification.data)
            .android.setChannelId('default_notification_channel_id') // e.g. the id you chose above
            // .android.setSmallIcon('@mipmap/ic_launcher') // create this icon in Android Studio
            // .android.setColor('red') // you can set a color here
            .android.setPriority(firebase.notifications.Android.Priority.High)
            .android.setVibrate([300])
            .android.setDefaults([
              firebase.notifications.Android.Defaults.Vibrate,
            ]);
          console.log('Notification:', localNotification);
          firebase
            .notifications()
            .displayNotification(localNotification)
            .catch((err) => console.error('Chay vao day android', err));
        } else if (Platform.OS === 'ios') {
          const localNotification = new firebase.notifications.Notification()
            .setNotificationId(notification.notificationId)
            .setTitle(notification.title)
            .setSubtitle(notification.subtitle)
            .setBody(notification.body)
            .setData(notification.data)
            .ios.setBadge(notification.ios.badge)
            .ios.setLaunchImage('@mipmap/ic_stat_ic_notification');

          firebase
            .notifications()
            .displayNotification(localNotification)
            .catch((err) => console.error('Chay vao day', err));
        }
        // this.getNotifyNumber();
      });

    /*
     * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
     * */
    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened((notificationOpen) => {
        this.props.onOpened(notificationOpen.notification);
      });

    /*
     * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
     * */
    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      this.props.onOpened(notificationOpen.notification);
    }
    /*
     * Triggered for data only payload in foreground
     * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      // process data message
      console.log('message---', message);
      this.props.onReceived(message);
    });
  }

  render() {
    return <View />;
  }
}

export default FirebaseNotification;
