import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { noop } from 'node-noop';
import { Field } from 'redux-form';

import { withStyles } from '@material-ui/core/styles';
import LoginButton from './LoginButton/LoginButton';
import TextInput from '../../TextInput/TextInput';
import PasswordInput from '../../PasswordInput/PasswordInput';
import Alert from '../../Alert/Alert';

const styles = theme => ({
  form: {
    position: 'relative',
    flexGrow: 1,
    marginTop: theme.spacing.unit * 2,
    marginBottom: theme.spacing.unit * 2,
  },

  alert: {
    position: 'absolute',
    top: -theme.spacing.unit * 7,
    paddingRight: theme.spacing.unit,
    paddingLeft: theme.spacing.unit,
  }
});

const renderField = ({ ...rest }) => (
  <div>
    {rest.type === 'password'
      ? <PasswordInput {...rest} />
      : <TextInput {...rest} />
    }
  </div>
);

const LoginForm = ({
  messages, submitting, handleSubmit, error, classes
}) => (
  <form className={classes.form} onSubmit={handleSubmit} autoComplete="off">
    {error && <Alert classNames={classes.alert} messages={messages} type={error} />}
    <FormattedMessage id="page.login.email.title" />
    <Field
      name="email"
      type="email"
      label="Email"
      component={renderField}
    />
    <FormattedMessage id="page.login.password.title" />
    <Field
      name="password"
      type="password"
      label="Password"
      component={renderField}
    />
    <LoginButton type="submit" disabled={submitting} />
  </form>
);
renderField.propTypes = {
  label: PropTypes.string
};

renderField.defaultProps = {
  label: ''
};

LoginForm.propTypes = {
  handleSubmit: PropTypes.func,
  submitting: PropTypes.bool,
  messages: PropTypes.shape({
  }),
  error: PropTypes.string,
};

LoginForm.defaultProps = {
  handleSubmit: noop,
  submitting: false,
  messages: {
    default: 'default message'
  },
  error: undefined,
};

export default withStyles(styles)(LoginForm);
