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

import { withSite } from '../../addons/Site';
import { validateEmail } from '../../lib';
import PasswordResetPending from './PasswordResetPending';

/* Interface */
const propTypes = {
  /** Event handler called when request is successful. */
  onRequested: PropTypes.func,

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

/**
 * Signin form with email and password fields
 * It validates email and password
 * @returns {Object} component
 */
export class PasswordRequestForm extends Component {
  state = {
    email: '',
    error: null,
    requestSent: false,
    isLoading: false,
  };

  /**
   * 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 });
  };

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

    const { email } = this.state;
    const { site } = this.props;

    if (!email) {
      this.showError('An email address must be entered');
      return;
    }

    if (!validateEmail(email)) {
      this.showError('The email address entered was invalid');
      return;
    }

    try {
      await site.req('identityprovider/email/resetrequest')
        .setParams({
          email,
          return_to: window.location.href,
        })
        .promise()
        .create();

      if (this.props.onRequested) {
        this.props.onRequested();
      }

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

  /**
   * Error setting for when any validation fails i.e weak password
   * @param {string} error - Value of error to set state to.
   * @returns {void}
   */
  showError = (error = null) => {
    this.setState({
      error,
      isLoading: false,
    });
  };

  render() {
    const { error, requestSent, isLoading } = this.state;

    if (requestSent) {
      return <PasswordResetPending />;
    }

    return (
      <Form
        error={ !!error }
        loading={ isLoading }
        onSubmit={ this.handleSubmit }
      >
        <h2>Enter your email address in the field below</h2>

        <p>If there&apos;s an account associated with this address we&apos;ll
          send the instructions</p>

        <Divider hidden />

        <Form.Input
          name="email"
          type="email"
          placeholder="Enter your email address"
          onChange={ this.handleChange }
        />

        <Message error content={ error } />

        <Form.Button primary circular size="large" type="submit">
          Reset Password
        </Form.Button>
      </Form>
    );
  }
}

PasswordRequestForm.propTypes = propTypes;

export default withSite(PasswordRequestForm);
