import { useState } from 'react';
import PropTypes from 'prop-types';
import ResetModalStepOne from './step-one';
import ResetModalStepTwo from './step-two';
import ResetModalStepSuccess from './step-success';
import { connect } from 'react-redux';
import { createResetRequest } from '../../../redux/actions/reset-request';
import { fetchStudentDecks } from '../../../redux/actions/student-deck';
import ResetModalStepError from './step-error';

function ResetModal(props) {
  const [step, setStep] = useState(1);
  const [error, setError] = useState(null);
  const { itemType, itemId, itemName, onClose } = props;

  const itemLabel = `${_[itemType]} ${itemName}`;

  if (error) {
    return (
      <ResetModalStepError
        itemLabel={itemLabel}
        error={error}
        onClose={() => {
          setStep(1);
          onClose();
        }}
      />
    );
  }

  if (step === 1) {
    return <ResetModalStepOne itemLabel={itemLabel} onClose={onClose} onNext={() => setStep(2)} />;
  }

  if (step === 2) {
    return (
      <ResetModalStepTwo
        onClose={onClose}
        onNext={async () => {
          try {
            await props.createResetRequest(itemType, itemId);
            setStep(0);
          } catch (error) {
            setError(error);
          }
        }}
      />
    );
  }

  if (step === 0) {
    return (
      <ResetModalStepSuccess
        itemLabel={itemLabel}
        onClose={() => {
          setStep(1);
          props.fetchStudentDecks();
          onClose();
        }}
      />
    );
  }

  return null;
}

const _ = { chapter: 'فصل', lesson: 'درس', deck: 'بسته' };

ResetModal.propTypes = {
  itemType: PropTypes.oneOf(['chapter', 'lesson', 'deck']).isRequired,
  itemId: PropTypes.number.isRequired,
  itemName: PropTypes.string.isRequired,
  onClose: PropTypes.func.isRequired,
  createResetRequest: PropTypes.func.isRequired,
  fetchStudentDecks: PropTypes.func.isRequired
};

export default connect(null, { createResetRequest, fetchStudentDecks })(ResetModal);
