import { Fragment } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Field, Form, Formik } from 'formik';
import Button from '../shared/buttons/button';
import FormInput from '../shared/forms/input';
import { required } from '../shared/forms/validations';
import { fetchCode } from '../../redux/actions/code';
import { updateOrderCode } from '../../redux/actions/order';

function Code(props) {
  return (
    <div className='my-4'>
      <Formik
        enableReinitialize
        initialValues={{ codeText: props.code ? props.code.text : '' }}
        onSubmit={async ({ codeText }, { setErrors }) => {
          const defaultErrorMessage = props.code
            ? 'حذف کد تخفیف انجام نشد.'
            : 'کد تخفیف وارد شده معتبر نمی‌باشد.';
          try {
            if (props.code) {
              await props.updateOrderCode(props.orderId, null);
            } else {
              await props.updateOrderCode(props.orderId, codeText);
            }
          } catch (error) {
            setErrors({ _error: error.message || defaultErrorMessage });
          }
        }}
      >
        {({ errors, dirty, isSubmitting }) => (
          <Fragment>
            <Form>
              <Field
                required
                inline
                disabled={!!props.code}
                name='codeText'
                label='کد تخفیف'
                component={FormInput}
                validate={[required]}
              />
              <Button
                color={props.code ? 'red' : 'blue'}
                inline
                type='submit'
                disabled={isSubmitting}
                content={props.code ? 'حذف کد تخفیف' : 'اعمال کد تخفیف'}
              />
              {dirty && errors._error && <p className='mt-3 mb-5 text-red-500'>{errors._error}</p>}
            </Form>
          </Fragment>
        )}
      </Formik>
    </div>
  );
}

Code.propTypes = {
  orderId: PropTypes.number.isRequired,
  code: PropTypes.object,
  fetchCode: PropTypes.func.isRequired,
  updateOrderCode: PropTypes.func.isRequired
};

export default connect(null, { fetchCode, updateOrderCode })(Code);
