/*global FB*/

import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import Button from 'shared/components/form/button';
import {loadFacebookSDK} from 'authentication/utils/facebook_sdk';

class FacebookButton extends PureComponent {
  static propTypes = {
    onAuthenticate: PropTypes.func.isRequired,
    action: PropTypes.oneOf(['login', 'register']).isRequired,
    opted_in: PropTypes.bool,
    remember_me: PropTypes.bool,
    setOauthData: PropTypes.func.isRequired,
    handleError: PropTypes.func,
    setError: PropTypes.func
  };

  componentDidMount() {
    loadFacebookSDK();
  }

  onClick = () => {
    if (this.props.setError) this.props.setError('');

    FB.login(
      response => {
        if (response.status === 'connected') {
          const result = this.props.onAuthenticate(this.props.action, {
            provider: 'facebook',
            access_token: response.authResponse.accessToken,
            opted_in: this.props.opted_in,
            remember_me: this.props.remember_me
          });

          FB.api(
            '/me',
            data => {
              this.props.setOauthData({
                access_token: response.authResponse.accessToken,
                provider: 'facebook',
                email: data.email
              });
            },
            {fields: 'email'}
          );

          this.props.handleError(result);
        }
      },
      {scope: 'email'}
    );
  };

  getButtonText() {
    if (this.props.action == 'login') return 'SIGN IN WITH FACEBOOK';
    if (this.props.action == 'register') return 'REGISTER WITH FACEBOOK';
  }

  render() {
    return (
      <>
        <Button
          className="mo-web-oauth-button mo-web-oauth-button--facebook"
          onClick={this.onClick}
        >
          <span className="mo-web-icon-facebook" />
          <span className="mo-web-oauth-button__text">
            {this.getButtonText()}
          </span>
        </Button>
      </>
    );
  }
}

export default FacebookButton;
