import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Divider, Form, Message } from 'semantic-ui-react';

import PasswordStrength from '../PasswordStrength';
import { withSite } from '../../addons/Site';

/* Interface */
const propTypes = {
  /** Reset token query parameter */
  token: PropTypes.string.isRequired,

  /** Event handler called when reset is successful. */
  onPasswordReset: PropTypes.func.isRequired,

  /**
   * StoryShare `Site`.
   * @private
   */
  site: PropTypes.object.isRequired,
};

/**
 * Component for setting new password
 * @returns {Object} component
 */
export class PasswordResponseForm extends Component {
  state = {
    passwordValid: false,
    password: '',
    error: '',
  };

  /**
   * Handle changes to input boxes
   * @param {ChangeEvent} event - React's original SyntheticEvent.
   * @param {string} event.name - Element name.
   * @param {string} event.value - Proposed value.
   * @returns {void}
   */
  handleChange = ({ target: { name, value } }) => {
    this.setState({ [name]: value });
  };

  /**
   * Handles password validation
   * @param {boolean} valid - Updates state if password is valid.
   * @returns {void}
   */
  handlePasswordValid = (valid) => this.setState({ passwordValid: valid });

  handleSubmit = async () => {
    const { site, token } = this.props;
    this.setState({ error: null, isLoading: true });

    const { password } = this.state;

    try {
      const result = await site.req('identityprovider/email/resetresponse')
        .setParams({
          password,
          token: token,
        })
        .promise()
        .create();

      if (result && result.search) {
        await site.login({ jwt: result.search });
      }

      this.props.onPasswordReset();
    } catch (e) {
      // eslint-disable-next-line max-len
      this.showError('An error occurred when trying to reset your password, please try again');
    }
  };

  /**
   * Displays an error in the form
   * @param {string} error - Value of error to set state to.
   * @returns {void}
   */
  showError = (error = null) => {
    this.setState({
      error,
      isLoading: false,
    });
  };

  render = () => {
    const { passwordValid, isLoading, error, password } = this.state;

    return (
      <Form
        error={ !!error }
        loading={ isLoading }
        onSubmit={ this.handleSubmit }
      >
        <h2>Enter new password</h2>

        <Divider hidden />

        <Form.Input
          name="password"
          onChange={ this.handleChange }
          placeholder="Enter a new password"
          type="password"
          value={ password }
        />
        <PasswordStrength
          password={ password }
          onValidate={ this.handlePasswordValid }
        />

        <Message error>{ error }</Message>

        <Form.Button
          circular
          disabled={ !passwordValid }
          primary
          size="large"
          type="submit"
        >
          Submit Password
        </Form.Button>
      </Form>
    );
  }
}

PasswordResponseForm.propTypes = propTypes;

export default withSite(PasswordResponseForm);
