import { Fragment } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Field, Form, Formik } from 'formik';
import Segment from '../shared/segment';
import { mobile, required } from '../shared/forms/validations';
import FormInput from '../shared/forms/input';
import Button from '../shared/buttons/button';
import { loginUser } from '../../redux/actions/auth';
import Alert from '../shared/alert';
import NavLink from '../shared/buttons/nav-link';
import ButtonGroup from '../shared/buttons/button-group';

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

  return (
    <Segment>
      <Formik initialValues={{ mobile: '', password: '' }} onSubmit={submit}>
        {({ errors, dirty }) => (
          <Fragment>
            {dirty && errors._error && <Alert content={errors._error} className='mt-3 mb-5' />}

            <Form className='grid grid-cols-1 gap-5 p-3'>
              <Field
                required
                id='username'
                name='mobile'
                label='شماره تلفن همراه'
                type='tel'
                placeholder='09121234567'
                component={FormInput}
                validate={mobile}
                autoComplete='username'
              />
              <Field
                required
                name='password'
                label='رمز عبور'
                type='password'
                component={FormInput}
                validate={required}
                autoComplete='current-password'
              />
              <ButtonGroup float>
                <Button type='submit' color='green' content='ورود' />
                <NavLink to='/forget-password' color='indigo' content='بازیابی رمز عبور' />
              </ButtonGroup>
            </Form>
          </Fragment>
        )}
      </Formik>
    </Segment>
  );
}

LoginForm.propTypes = {
  loginUser: PropTypes.func.isRequired
};

export default connect(null, { loginUser })(LoginForm);
