import React from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { injectIntl, FormattedMessage, defineMessages } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { otpVerify, verifyCredentials, switchAccount } from 'soapbox/actions/auth';
import { SimpleInput } from 'soapbox/features/forms';
import PropTypes from 'prop-types';

const messages = defineMessages({
  otpCodeHint: { id: 'login.fields.otp_code_hint', defaultMessage: 'Enter the two-factor code generated by your phone app or use one of your recovery codes' },
  otpCodeLabel: { id: 'login.fields.otp_code_label', defaultMessage: 'Two-factor code:' },
});

export default @connect()
@injectIntl
class OtpAuthForm extends ImmutablePureComponent {

  state = {
    isLoading: false,
    code_error: '',
    shouldRedirect: false,
  }

  static propTypes = {
    intl: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired,
    mfa_token:  PropTypes.string,
  };

  getFormData = (form) => {
    return Object.fromEntries(
      Array.from(form).map(i => [i.name, i.value]),
    );
  }

  handleSubmit = (event) => {
    const { dispatch, mfa_token } = this.props;
    const { code } = this.getFormData(event.target);
    dispatch(otpVerify(code, mfa_token)).then(({ access_token }) => {
      this.setState({ code_error: false });
      return dispatch(verifyCredentials(access_token));
    }).then(account => {
      this.setState({ shouldRedirect: true });
      return dispatch(switchAccount(account.id));
    }).catch(error => {
      this.setState({ isLoading: false });
      if (error.response.data.error === 'Invalid code') {
        this.setState({ code_error: true });
      }
    });
    this.setState({ isLoading: true });
    event.preventDefault();
  }

  render() {
    const { intl } = this.props;
    const { code_error, shouldRedirect } = this.state;

    if (shouldRedirect) return <Redirect to='/' />;

    return (
      <form className='simple_form new_user otp-auth' method='post' onSubmit={this.handleSubmit}>
        <fieldset disabled={this.state.isLoading}>
          <div className='fields-group'>
            <div className='input email optional user_email'>
              <h1 className='otp-login'>
                <FormattedMessage id='login.otp_log_in' defaultMessage='OTP Login' />
              </h1>
            </div>
            <div className='input code optional otp_code'>
              <SimpleInput
                label={intl.formatMessage(messages.otpCodeLabel)}
                hint={intl.formatMessage(messages.otpCodeHint)}
                name='code'
                type='text'
                autoComplete='off'
                onChange={this.onInputChange}
                required
              />
            </div>
          </div>
        </fieldset>
        { code_error &&
          <div className='error-box'>
            <FormattedMessage id='login.otp_log_in.fail' defaultMessage='Invalid code, please try again.' />
          </div>
        }
        <div className='actions'>
          <button name='button' type='submit' className='btn button button-primary'>
            <FormattedMessage id='login.log_in' defaultMessage='Log in' />
          </button>
        </div>
      </form>
    );
  }

}
