import { Fragment } from 'react';
import { connect } from 'react-redux';
import { Field, Form, Formik } from 'formik';
import Button from '../shared/buttons/button';
import Segment from '../shared/segment';
import Alert from '../shared/alert';
import FormInput from '../shared/forms/input';
import { atLeastNChars } from '../shared/forms/validations';
import { updateStudentNickName } from '../../redux/actions/student';
import PropTypes from 'prop-types';

function UpdateNickNameForm(props) {
  async function submit({ nickName }, { setErrors }) {
    try {
      await props.updateStudentNickName(nickName);
    } catch (e) {
      setErrors(e.data.detail || e.data);
    }
  }

  return (
    <Segment className='mx-auto sm:w-2/3 lg:w-1/2'>
      <p className='text-center'>برای دیدن رتبه‌ها اول باید یک نام مستعار انتخاب کنید:</p>
      <Formik initialValues={{ nickName: '' }} 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
                name='nickName'
                label='نام مستعار'
                component={FormInput}
                validate={atLeastNChars(4)}
              />
              <Button type='submit' color='green' content='ثبت' />
            </Form>
          </Fragment>
        )}
      </Formik>
    </Segment>
  );
}

UpdateNickNameForm.propTypes = {
  updateStudentNickName: PropTypes.func.isRequired
};

export default connect(null, { updateStudentNickName })(UpdateNickNameForm);
