import { Component, Fragment } from 'react';
import { Field, Form, Formik } from 'formik';
import PropTypes from 'prop-types';
import Segment from '../shared/segment';
import Divider from '../shared/divider';
import Alert from '../shared/alert';
import Button from '../shared/buttons/button';
import FormInput from '../shared/forms/input';
import { password, required } from '../shared/forms/validations';

class PasswordForm extends Component {
  submit = async ({ password }, { setErrors }) => {
    try {
      await this.props.onSubmit(password);
    } catch (error) {
      const errorMessage = error.message || 'تغییر رمز عبور انجام نشد.';
      setErrors({ _error: errorMessage });
    }
  };

  validate = values => {
    const errors = {};
    if (values.password !== values.password2) errors.password2 = 'رمزهای عبور غیر یکسان هستند.';
    return errors;
  };

  render() {
    return (
      <Segment>
        <Divider horizontal content='فرم تغییر رمز عبور' className='mb-5' />

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

              <Form>
                <Field
                  required
                  name='password'
                  type='password'
                  label='رمز عبور جدید'
                  component={FormInput}
                  validate={[required, password]}
                  className='my-4'
                />
                <Field
                  required
                  name='password2'
                  type='password'
                  label='تکرار رمز عبور جدید'
                  placeholder='رمز عبور جدید خود را مجدد وارد نمایید'
                  component={FormInput}
                  validate={[required, password]}
                />
                <Button
                  type='submit'
                  disabled={!dirty || isSubmitting}
                  content='تغییر رمز عبور'
                  className='my-2 mr-auto'
                />
              </Form>
            </Fragment>
          )}
        </Formik>
      </Segment>
    );
  }
}

PasswordForm.propTypes = {
  onSubmit: PropTypes.func.isRequired
};

export default PasswordForm;
