import { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { useToasts } from 'react-toast-notifications';
import PropTypes from 'prop-types';
import MainLayout from '../layouts/main';
import MobileForm from './mobile-form';
import SMSKeyForm from '../shared/sms-key-form';
import PasswordForm from './password-form';
import Alert from '../shared/alert';
import {
  checkSMSKeyRequest,
  forgetPasswordRequest,
  resetPasswordRequest
} from '../../redux/actions/user';
import { loginUser } from '../../redux/actions/auth';
import { selectIsAuthenticated } from '../../redux/selectors/auth';
import { DEFAULT_DECKS_ROUTE } from '../utils/index';

function ForgetPasswordPage(props) {
  const [step, setStep] = useState(0);
  const [mobile, setMobile] = useState(null);
  const [uid, setUID] = useState(null);
  const [token, setToken] = useState(null);
  const [error, setError] = useState(null);

  const { addToast } = useToasts();
  if (props.isAuthenticated) return <Redirect to={DEFAULT_DECKS_ROUTE} />;

  function renderForm(step) {
    if (step === MOBILE) {
      return (
        <MobileForm
          onSubmit={async function (mobile) {
            const {
              payload: { uid }
            } = await props.forgetPasswordRequest(mobile);
            setMobile(mobile);
            setUID(uid);
            setStep(SMS_KEY);
          }}
        />
      );
    }

    if (step === SMS_KEY) {
      return (
        <SMSKeyForm
          back
          mobile={mobile}
          onSubmit={async function (smsKey) {
            const {
              payload: { token }
            } = await props.checkSMSKeyRequest(uid, smsKey);
            setToken(token);
            setStep(PASSWORD);
          }}
          onResend={async function () {
            const {
              payload: { uid }
            } = await props.forgetPasswordRequest(mobile);
            setUID(uid);
          }}
          onBack={setStep.bind(null, MOBILE)}
          onError={setError}
        />
      );
    }

    if (step === PASSWORD) {
      return (
        <PasswordForm
          onSubmit={async function (password) {
            const { error } = await props.resetPasswordRequest(uid, token, password);
            if (!error) {
              addToast('رمز عبور شما با موفقیت تغییر کرد.', { appearance: 'success' });
              await props.loginUser(mobile, password);
              setStep(MOBILE);
            }
          }}
        />
      );
    }

    return null;
  }

  return (
    <MainLayout loginRequired={false} consultPackageRequired={false} packageRequired={false}>
      {error ? (
        <Alert content={error} className='mt-3 mb-5' />
      ) : (
        <div className='mx-auto w-full sm:w-4/5 lg:w-3/5'>{renderForm(step)}</div>
      )}
    </MainLayout>
  );
}

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

ForgetPasswordPage.propTypes = {
  isAuthenticated: PropTypes.bool.isRequired,
  checkSMSKeyRequest: PropTypes.func.isRequired,
  forgetPasswordRequest: PropTypes.func.isRequired,
  resetPasswordRequest: PropTypes.func.isRequired,
  loginUser: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  return { isAuthenticated: selectIsAuthenticated(state) };
}

export default connect(mapStateToProps, {
  checkSMSKeyRequest,
  forgetPasswordRequest,
  resetPasswordRequest,
  loginUser
})(ForgetPasswordPage);
