import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Screen from 'app/components/Screen';
import {
  authLogout,
  authDeletePushNotificationToken,
} from 'app/shared/actions/auth';
import {personalUpdateData} from 'app/shared/actions/personal';
import {View} from 'react-native';
import messaging from '@react-native-firebase/messaging';
import NavigationService from '../../shared/services/NavigationService';

class BackToLoginScreen extends Screen {
  state = {
    token: '',
  };

  async componentDidMount() {
    await this.getToken();

    // Wait for state update
    setTimeout(() => this.logout(), 0);
  }

  async getToken() {
    const token = await messaging().getToken();

    this.setState({
      ...this.state,
      token: token,
    });
  }

  logout() {
    this.props.authDeletePushNotificationToken(this.state.token);
    this.props.authLogout();
    NavigationService.navigate('login');
  }

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

BackToLoginScreen.propTypes = {
  auth: PropTypes.object,
  authLogout: PropTypes.func,
  personal: PropTypes.object,
};

const mapStateToProps = (state) => {
  return {
    auth: state.auth,
    personal: state.personal,
  };
};

const mapDispatchToProps = {
  authLogout,
  authDeletePushNotificationToken,
  personalUpdateData,
};

export default connect(mapStateToProps, mapDispatchToProps)(BackToLoginScreen);
