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

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

/* Interface */
const propTypes = {
  /** Event handler called when signin is successful. */
  onSignIn: PropTypes.func.isRequired,

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

/**
 * Signin form with email and password fields
 * It checks if email exists and password matches user record
 * @returns {Object} component
 */
export class SignInForm extends Component {
  state = {
    email: '',
    error: null,
    isLoading: false,
    password: '',
  };

  /**
   * Handle inputs change by updating value in local state
   * @param {SyntheticEvent} event - React's original SyntheticEvent.
   * @param {Object} data - All props and proposed value.
   * @returns {void}
   */
  handleChange = (event, { name, value }) =>
    this.setState({ [name]: value });

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

  handleSubmit = async () => {
    const { site } = this.props;

    if (!this.isComplete()) {
      return;
    }

    this.setState({ error: null, isLoading: true });

    const { email, password } = this.state;

    if (!validateEmail(email.trim())) {
      this.showError('Supplied email address is not valid');
      return;
    }

    try {
      await site.login({ email: email.trim(), password });
      this.props.onSignIn();
    } catch (err) {
      this.showError('Incorrect credentials');
    }
  };

  isComplete = () => {
    const { email, password } = this.state;
    return email.trim() && password;
  };

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

    return (
      <Form
        onSubmit={ this.handleSubmit }
        loading={ isLoading }
        error={ !!error }
      >
        <p>If you&apos;ve registered with us, sign in here:</p>

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

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

        <Message error content={ error } />

        <Form.Field>
          <Form.Button
            circular
            disabled={ !this.isComplete() }
            primary
            size="large"
            type="submit"
          >
            Go
          </Form.Button>
        </Form.Field>
      </Form>
    );
  };
}

SignInForm.propTypes = propTypes;

export default withSite(SignInForm);
