import { Fragment, useEffect } from 'react';
import { connect } from 'react-redux';
import { toast, ToastContainer, Zoom } from 'react-toastify';
import Toast from '../../shared/toast';
import { removeError } from '../../../redux/actions/errors';
import 'react-toastify/dist/ReactToastify.css';

function ErrorBoundary(props) {
  const { errors, removeError } = props;

  useEffect(() => {
    for (let i = 0; i < errors.length; i++) {
      const {
        id,
        error: { status, statusText, data }
      } = errors[i];
      toast.error(<Toast errorCode={status} errorText={statusText} errorData={data} />);
      removeError(id);
    }
  }, [errors, removeError]);

  return (
    <Fragment>
      {props.children}
      <ToastContainer
        position='bottom-left'
        autoClose={10000}
        hideProgressBar={false}
        rtl={true}
        transition={Zoom}
      />
    </Fragment>
  );
}

function mapStateToProps({ errors }) {
  return { errors };
}

export default connect(mapStateToProps, { removeError })(ErrorBoundary);
