/**
 * Routes:
 *   - ./src/pages/routes
 */
import React, { useEffect } from 'react';
import { Spin } from 'antd';
import { connect, DispatchProp } from 'dva';
import FittedImage from 'react-fitted-image';
import { CheckModelState, PageStep } from './model';
import { PageState } from '@/types/common';
import Header from '@/components/Header';
import bgPic from '@/assets/bg_login.png';
import styles from './style.less';
import CheckPage from './check';
import LoginPage from './login';
import RegisterPage from './register';
import ResetPage from './reset';
import { formatMessage } from 'umi-plugin-locale';

const Page: React.FC<DispatchProp & CheckModelState> = ({
  pageState,
  pageStep,
  dispatch,
}) => {
  useEffect(() => {
    dispatch({ type: 'check/load' });
  }, []);

  if (pageState === PageState.Pending) {
    return (
      <div className={styles.loading}><Spin /></div>
    );
  }

  if (pageState === PageState.Failure) {
    return (
      <div
        onClick={() => dispatch({ type: 'check/load' })}
        className={styles.error}
      >{formatMessage({ id: 'app.error' })}</div>
    );
  }

  let title;
  if (pageStep === PageStep.Register) {
    title = formatMessage({ id: 'check.titleRegister' });
  } else if (pageStep === PageStep.Reset || pageStep === PageStep.ResetSuccess) {
    title = formatMessage({ id: 'check.titleReset' });
  }

  return (
    <div className={styles.check}>
      {
        pageStep !== PageStep.Check &&
         <Header
           title={title}
           className={styles.header}
           onReturn={() => dispatch({ type: 'check/back' })}
         />
      }

      {(
        pageStep === PageStep.Check ||
        pageStep === PageStep.Login
      ) && (
        <div className="cover">
          <div className="image">
            <FittedImage fit="contain" src={bgPic} />
          </div>
          <span>{formatMessage({ id: 'app.name' })}</span>
        </div>
      )}

      {{
        [PageStep.Check]: <CheckPage />,
        [PageStep.Login]: <LoginPage />,
        [PageStep.Register]: <RegisterPage />,
        [PageStep.Reset]: <ResetPage />,
        [PageStep.ResetSuccess]: null,
      }[pageStep]}
    </div>
  );
}

export default connect(
  ({ check } : any) => ({ ...check })
)(Page);
