import { useState } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import MobileForm from './mobile-form';
import RegisterForm from './register-form';
import SMSKeyForm from '../shared/sms-key-form';
import Alert from '../shared/alert';
import Fetcher from '../shared/fetches/fetcher';
import { fetchActiveStudentTypes } from '../../redux/actions/student-type';
import {
  checkSmsKeyRequest,
  createTempUser,
  sendSmsKeyRequest
} from '../../redux/actions/temp-user';

function RegisterContent(props) {
  const [step, setStep] = useState(0);
  const [mobile, setMobile] = useState(null);
  const [authKey, setAuthKey] = useState(null);
  const [error, setError] = useState(null);

  if (error) return <Alert content={error} />;

  if (step === MOBILE) {
    return (
      <div className='w-100 mx-auto md:w-4/5 lg:w-3/5'>
        <MobileForm
          onSubmit={async function (mobile) {
            await props.createTempUser(mobile);
            setMobile(mobile);
            setStep(SMS_KEY);
          }}
        />
      </div>
    );
  }

  if (step === SMS_KEY) {
    return (
      <div className='w-100 mx-auto md:w-4/5 lg:w-3/5'>
        <SMSKeyForm
          back
          mobile={mobile}
          onSubmit={async smsKey => {
            const {
              payload: { authKey }
            } = await props.checkSmsKeyRequest(mobile, smsKey);
            setAuthKey(authKey);
            setStep(REGISTER);
          }}
          onResend={async () => await props.sendSmsKeyRequest(mobile)}
          onBack={() => setStep(MOBILE)}
          onError={setError}
        />
      </div>
    );
  }

  if (step === REGISTER) {
    return (
      <Fetcher action={fetchActiveStudentTypes} stateSelector={state => state.studentTypes}>
        {studentTypes => (
          <RegisterForm mobile={mobile} authKey={authKey} studentTypes={studentTypes} />
        )}
      </Fetcher>
    );
  }

  return null;
}

const [MOBILE, SMS_KEY, REGISTER] = [0, 1, 2];

RegisterContent.propTypes = {
  createTempUser: PropTypes.func.isRequired,
  sendSmsKeyRequest: PropTypes.func.isRequired,
  checkSmsKeyRequest: PropTypes.func.isRequired
};

export default connect(null, { createTempUser, sendSmsKeyRequest, checkSmsKeyRequest })(
  RegisterContent
);
