import React from 'react';
import { Redirect } from 'react-router-dom';

import { fetchVerificationConfig } from 'soapbox/actions/verification';
import { useAppDispatch, useAppSelector } from 'soapbox/hooks';

import Registration from './registration';
import AgeVerification from './steps/age-verification';
import EmailVerification from './steps/email-verification';
import SmsVerification from './steps/sms-verification';

export enum ChallengeTypes {
  EMAIL = 'email',
  SMS = 'sms',
  AGE = 'age',
}

const verificationSteps = {
  email: EmailVerification,
  sms: SmsVerification,
  age: AgeVerification,
};

const Verification = () => {
  const dispatch = useAppDispatch();

  const isInstanceReady = useAppSelector((state) => state.verification.instance.get('isReady') === true);
  const isRegistrationOpen = useAppSelector(state => state.verification.instance.get('registrations') === true);
  const currentChallenge = useAppSelector((state) => state.verification.currentChallenge as ChallengeTypes);
  const isVerificationComplete = useAppSelector((state) => state.verification.isComplete);
  const StepToRender = verificationSteps[currentChallenge];

  React.useEffect(() => {
    dispatch(fetchVerificationConfig());
  }, []);

  if (isInstanceReady && !isRegistrationOpen) {
    return <Redirect to='/' />;
  }

  if (isVerificationComplete) {
    return (
      <Registration />
    );
  }

  if (!currentChallenge) {
    return null;
  }

  return (
    <StepToRender />
  );
};

export default Verification;
