import React, { memo, useState, useEffect } from 'react';
import classNames from 'classnames';
import useLang from '@Hooks/useLang';
import useDidMount from '@Hooks/useDidMount';
import useReduxApi from '@Hooks/useReduxApi';
import useMappedState from '@Hooks/useMappedState';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Loading from '@Components/Base/Loading';
import BASE_URL from '@Base/url';
import Styles from './index.module.css';

const GUEST_URL = BASE_URL.GUEST;

function SignIn(): React.ReactElement {
  /* Global & Local State */
  const { i18n } = useLang();
  const reduxUser = useReduxApi('user');
  const storeUser = useMappedState((state) => state.user);
  const storeGlobal = useMappedState((state) => state.global);
  const [isFirstInitial, setIsFirstInitial] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  /* Functions */
  const onSubmitSSO = (): void => {
    const backUrl = `${window.location.origin}${GUEST_URL.BASE_PAGE_OAUTH}`;
    setIsLoading(true);
    reduxUser('getUserSSO', [backUrl]);
  };
  const initialize = (): void => {
    if (storeGlobal.globalEnv.env.EnvName === 'prod') {
      onSubmitSSO();
    }
    setIsFirstInitial(true);
  };
  /* Hooks */
  useDidMount(() => {
    initialize();
  });
  useEffect(() => {
    if (!isFirstInitial) return;
    if (storeUser.userOAuth.url) {
      window.location.href = storeUser.userOAuth.url;
    }
    setIsLoading(false);
  }, [storeUser.userOAuth]);
  /* Main */
  return (
    <div className={classNames(Styles.signInContainer)}>
      <div className={classNames(Styles.signInPanelContainer)}>
        <div className={classNames(Styles.signInTitleContainer)}>
          <Typography className={classNames(Styles.signInTitleMainStyle)} variant="h1" color="textPrimary">
            {i18n.t('frontend.local.signin.logintitle')}
          </Typography>
        </div>
        <div className={classNames(Styles.signInActionContainer)}>
          <Button
            className={classNames(Styles.signInActionButtonStyle)}
            variant="contained"
            color="primary"
            onClick={onSubmitSSO}
          >
            {i18n.t('frontend.global.operation.sso')}
          </Button>
        </div>
      </div>
      <Loading typePosition="absolute" typeZIndex={20000} typeIcon="line:fix" isLoading={isLoading} />
    </div>
  );
}

export default memo(SignIn);
