import { connect } from 'react-redux';
import { Field, Form, Formik } from 'formik';
import PropTypes from 'prop-types';
import Modal from '../shared/modal';
import FormSelect from '../shared/forms/select';
import FormTextArea from '../shared/forms/textarea';
import Button from '../shared/buttons/button';
import { required } from '../shared/forms/validations';
import { createReport } from '../../redux/actions/report';
import { useToasts } from 'react-toast-notifications';
import { useState } from 'react';
import Segment from '../shared/segment';

function ReportModal(props) {
  const [error, setError] = useState('');
  const { addToast } = useToasts();

  async function submit(values) {
    try {
      setError('');
      await props.createReport(values);
      addToast('با تشکر، گزارش خطای شما ثبت گردید.', { appearance: 'success' });
      props.onClose();
    } catch (e) {
      setError(e.statusText);
    }
  }

  return (
    <Modal
      showModal={props.showModal}
      onClose={props.onClose}
      header='فرم گزارش خطا'
      body={
        <Formik initialValues={{ card: props.cardId, type: '', description: '' }} onSubmit={submit}>
          <Form id='report-form' className='flex flex-col gap-3'>
            {error && (
              <Segment
                color='red'
                backgroundColor='red'
                className='text-center font-medium text-red-500'
              >
                <p>{error}</p>
                <p>لطفا مدتی بعد مجددا تلاش کنید.</p>
              </Segment>
            )}
            <input type='hidden' id='card' name='card' />
            <Field
              required
              name='type'
              label='نوع خطا'
              component={FormSelect}
              validate={required}
              options={types}
            />
            <Field
              required
              name='description'
              label='توضیحات'
              component={FormTextArea}
              validate={required}
              rows={5}
            />
          </Form>
        </Formik>
      }
      footer={
        <div className='mx-3 flex justify-between gap-2'>
          <Button
            type='submit'
            form='report-form'
            color='green'
            content='ثبت گزارش'
            className='grow'
          />
          <Button color='red' content='بازگشت' onClick={props.onClose} className='grow' />
        </div>
      }
    />
  );
}

const types = [
  { name: 'Scientific', text: 'علمی', value: 'Scientific' },
  { name: 'Typo', text: 'نگارشی', value: 'Typo' },
  { name: 'Other', text: 'سایر', value: 'Other' }
];

ReportModal.propTypes = {
  cardId: PropTypes.number.isRequired,
  showModal: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  createReport: PropTypes.func.isRequired
};

export default connect(null, { createReport })(ReportModal);
