/*global amazon*/

import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import Button from 'shared/components/form/button';
import {loadAmazonSDK} from 'authentication/utils/amazon_sdk';
import {getCurrentEnv} from 'shared/utils/common';

class AmazonButton 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() {
    loadAmazonSDK();
  }

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

    const options = {
      scope: 'profile payments:widget payments:shipping_address'
    };
    amazon.Login.setSandboxMode(getCurrentEnv() !== 'production');
    amazon.Login.authorize(options, response => {
      if (response.access_token) {
        const result = this.props.onAuthenticate(this.props.action, {
          provider: 'amazon',
          access_token: response.access_token,
          opted_in: this.props.opted_in,
          remember_me: this.props.remember_me
        });

        amazon.Login.retrieveProfile(response.access_token, resp =>
          this.props.setOauthData({
            access_token: response.access_token,
            email: resp.profile.PrimaryEmail,
            provider: 'amazon'
          })
        );

        this.props.handleError(result);
      }
    });
  };

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

  render() {
    return (
      <>
        <Button
          className="mo-web-oauth-button mo-web-oauth-button--amazon"
          onClick={this.onClick}
        >
          <span className="mo-web-icon-amazon" />
          <span className="mo-web-oauth-button__text">
            {this.getButtonText()}
          </span>
        </Button>
        <div className="amazon-info">
          Sign in with your Amazon account details to use your saved delivery
          and payment information.
        </div>
      </>
    );
  }
}

export default AmazonButton;
