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 {
  introducerCode,
  required,
  requiredTermsAndConditions
} from '../../shared/forms/validations';
import { fetchIntroducerCode } from '../../../redux/actions/introducer_code';
import { createStudent } from '../../../redux/actions/student';
import Loader from '../../shared/loader';
import { fetchActiveStudentTypes } from '../../../redux/actions/student-type';

class CreateStudentForm extends Component {
  componentDidMount() {
    this.props.fetchActiveStudentTypes();
  }

  submit = async (values, { setErrors }) => {
    const { 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.createStudent({ ...validatedValues, introducerCode });
    } catch (error) {
      setErrors(error.data.detail || error.data);
    }
  };

  render() {
    if (this.props.studentTypes.length === 0) return <Loader />;

    const STUDENT_TYPE_OPTIONS = this.props.studentTypes.map(({ id, name }) => ({
      name,
      value: id,
      text: name
    }));

    return (
      <Segment>
        <Formik
          initialValues={{
            type: '',
            notify: true,
            termsAndConditions: false,
            introducerCodeText: ''
          }}
          onSubmit={this.submit}
        >
          {({ errors, dirty, isSubmitting }) => (
            <Fragment>
              {dirty && errors._error && <Alert content={errors._error} className='mt-3 mb-5' />}
              <Form noValidate className='flex flex-col justify-center gap-6'>
                <Field
                  required
                  name='type'
                  label='وضعیت تحصیلی'
                  component={FormSelect}
                  options={STUDENT_TYPE_OPTIONS}
                  validate={required}
                  className='mx-auto w-full sm:w-2/3 lg:w-1/2 xl:w-1/3'
                />
                <Field
                  name='introducerCodeText'
                  label='کد معرف'
                  component={FormInput}
                  maxLength={6}
                  validate={introducerCode}
                  autoComplete='off'
                  className='mx-auto my-6 w-full sm:max-w-[240px]'
                />
                <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>
    );
  }
}

CreateStudentForm.propTypes = {
  studentTypes: PropTypes.array.isRequired,
  createStudent: PropTypes.func.isRequired,
  fetchActiveStudentTypes: PropTypes.func.isRequired,
  fetchIntroducerCode: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  return { studentTypes: state.studentTypes.data };
}

export default connect(mapStateToProps, {
  createStudent,
  fetchActiveStudentTypes,
  fetchIntroducerCode
})(CreateStudentForm);
