import { compose } from 'redux';
import { connect } from 'react-redux';
import { Field, reduxForm, reset, SubmissionError } from 'redux-form';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import Alert from 'react-bootstrap/Alert';
import FormInput from '../shared/forms/input';
import { mobile, required } from '../shared/forms';
import { loginUser } from '../../redux/actions/auth';
import Segment from '../shared/segment';

function LoginForm(props) {
  const { handleSubmit, pristine, submitting, error } = props;

  return (
    <Segment>
      {/* form error */}
      {error && !pristine && (
        <Alert variant='danger' className='text-center'>
          {error}
        </Alert>
      )}

      {/* form */}
      <Form onSubmit={handleSubmit(submit.bind(null, props))}>
        <Field
          required
          name='mobile'
          label='شماره تلفن همراه'
          type='tel'
          placeholder='09121234567'
          component={FormInput}
          validate={[required, mobile]}
        />
        <Field
          required
          name='password'
          label='رمز عبور'
          type='password'
          component={FormInput}
          validate={required}
        />
        <Button type='submit' disabled={pristine || submitting}>
          ورود
        </Button>
      </Form>
    </Segment>
  );
}

async function submit(props, { mobile, password }) {
  try {
    await props.loginUser(mobile, password);
    await props.reset();
  } catch (error) {
    const errorMessage = error.message || 'شماره تلفن یا رمز عبور نادرست است.';
    throw new SubmissionError({ _error: errorMessage });
  }
}

export default compose(
  connect(null, { loginUser, reset }),
  reduxForm({ form: 'login' })
)(LoginForm);
