import { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Field, Form, Formik } from 'formik';
import Segment from '../shared/segment';
import Button from '../shared/buttons/button';
import Alert from '../shared/alert';
import FormInput from '../shared/forms/input';
import FormSelect from '../shared/forms/select';
import FormCheckbox from '../shared/forms/checkbox';
import {
  gender,
  introducerCode,
  password,
  persian,
  required,
  requiredTermsAndConditions
} from '../shared/forms/validations';
// import {normalizeName} from '../shared/forms/normalizers';
import { registerUser } from '../../redux/actions/auth';
import { fetchIntroducerCode } from '../../redux/actions/introducer_code';

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

  submit = async (values, { setErrors }) => {
    const { rePassword, termsAndConditions, introducerCodeText, ...validatedValues } = values;

    let introducerCode = null;
    if (introducerCodeText) {
      try {
        const { payload } = await this.props.fetchIntroducerCode(introducerCodeText);
        introducerCode = payload.id;
      } catch (error) {
        setErrors({ introducerCodeText: error.data.detail || error.data });
        return;
      }
    }

    try {
      await this.props.registerUser({
        ...validatedValues,
        introducerCode,
        mobile: this.props.mobile,
        authKey: this.props.authKey
      });
    } catch (error) {
      setErrors(error.data.detail || error.data);
    }
  };

  render() {
    const STUDENT_TYPE_OPTIONS = this.props.studentTypes.map(({ id, name }) => ({
      name,
      value: id,
      text: name
    }));
    return (
      <Segment>
        <Formik
          initialValues={{
            mobile: this.props.mobile,
            authKey: this.props.authKey,
            firstName: '',
            lastName: '',
            gender: '',
            password: '',
            rePassword: '',
            type: '',
            notify: true,
            termsAndConditions: false,
            introducerCodeText: ''
          }}
          onSubmit={this.submit}
          validate={this.validate}
        >
          {({ errors, dirty, isSubmitting }) => (
            <Fragment>
              {dirty && errors._error && <Alert content={errors._error} className='mt-3 mb-5' />}
              <Form noValidate>
                <input type='hidden' id='username' name='mobile' />
                <input type='hidden' id='authKey' name='authKey' />
                <div className='grid grid-cols-2 gap-5 p-3'>
                  <Field
                    required
                    name='firstName'
                    label='نام'
                    component={FormInput}
                    validate={persian}
                    // normalize={normalizeName}
                  />
                  <Field
                    required
                    name='lastName'
                    label='نام خانوادگی'
                    component={FormInput}
                    validate={persian}
                    // normalize={normalizeName}
                  />
                  <Field
                    required
                    name='gender'
                    label='جنسیت'
                    component={FormSelect}
                    options={GENDER_OPTIONS}
                    validate={gender}
                  />
                  <Field
                    required
                    name='type'
                    label='وضعیت تحصیلی'
                    component={FormSelect}
                    options={STUDENT_TYPE_OPTIONS}
                    validate={required}
                  />
                  <Field
                    required
                    name='password'
                    label='رمز عبور'
                    type='password'
                    component={FormInput}
                    validate={password}
                    autoComplete='new-password'
                  />
                  <Field
                    required
                    name='rePassword'
                    label='تائید رمز عبور'
                    type='password'
                    component={FormInput}
                    validate={required}
                    autoComplete='off'
                  />
                  <div className='col-span-2 mx-auto my-6'>
                    <Field
                      name='introducerCodeText'
                      label='کد معرف'
                      component={FormInput}
                      maxLength={6}
                      validate={introducerCode}
                      autoComplete='off'
                    />
                  </div>
                </div>
                <Field
                  name='notify'
                  label={
                    <Fragment>
                      مایل به دریافت
                      <span className='font-medium'> پیامک های اطلاع رسانی </span>
                      سامانه فلش کارت های مدمشاور شامل
                      <span className='font-medium'> پکیج های جدید </span>و
                      <span className='font-medium'> کدهای تخفیف </span>
                      هستم.
                    </Fragment>
                  }
                  component={FormCheckbox}
                />
                <Field
                  required
                  name='termsAndConditions'
                  label={
                    <Fragment>
                      <Link to='/terms-and-conditions' className='text-indigo-600'>
                        شرایط و قوانین{' '}
                      </Link>
                      <span>را مطالعه کرده‌ام و آن‌ها را می‌پذیرم.</span>
                    </Fragment>
                  }
                  component={FormCheckbox}
                  validate={requiredTermsAndConditions}
                />
                <Button
                  type='submit'
                  disabled={!dirty || isSubmitting}
                  content='تایید'
                  className='col-span-3 my-4 mr-auto ml-2'
                />
              </Form>
            </Fragment>
          )}
        </Formik>
      </Segment>
    );
  }
}

const GENDER_OPTIONS = [
  { name: 'مرد', text: 'مرد', value: 'M' },
  { name: 'زن', text: 'زن', value: 'F' }
];

RegisterForm.propTypes = {
  mobile: PropTypes.string.isRequired,
  studentTypes: PropTypes.array.isRequired,
  authKey: PropTypes.string.isRequired,
  registerUser: PropTypes.func.isRequired,
  fetchIntroducerCode: PropTypes.func.isRequired
};

export default connect(null, { registerUser, fetchIntroducerCode })(RegisterForm);
