import PropTypes from 'prop-types';
import React from 'react';
import { Form, Icon } from 'antd';
import { CapInput, CapButton } from '@capillarytech/cap-ui-library';
import { injectIntl, intlShape } from 'react-intl';
import messages from './messages';
const FormItem = Form.Item;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.authenticate(values);
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem className="login-form-item">
          {getFieldDecorator('username', {
            rules: [{ required: true, message: this.props.intl.formatMessage(messages.inputUsernameMandatory) }],
          })(
            <CapInput prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder={this.props.intl.formatMessage(messages.username)} />
          )}
        </FormItem>
        <FormItem className="login-form-item">
          {getFieldDecorator('password', {
            rules: [{ required: true, message: this.props.intl.formatMessage(messages.inputPasswordMandatory) }],
          })(
            <CapInput prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder={this.props.intl.formatMessage(messages.password)} />
          )}
        </FormItem>
        {this.props.isError
        ? <FormItem>
          <span style={{color: "red"}}>{this.props.intl.formatMessage(messages.invalidCredentials)}</span>
        </FormItem>
        : null
        }
        <FormItem>
          <CapButton loading={this.props.loginInProgress} type="primary" htmlType="submit" className="login-form-button">
            Log in
          </CapButton>
        </FormItem>
      </Form>
    );
  }
}

NormalLoginForm.propTypes = {
  authenticate: PropTypes.func.isRequired,
  loginInProgress: PropTypes.bool,
  isError: PropTypes.bool,
  form: PropTypes.object,
  intl: intlShape.isRequired,
};

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
export default injectIntl(WrappedNormalLoginForm);
