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

function Home(): React.ReactElement {
  /* Global & Local State */
  const reduxUser = useReduxApi('user');
  const storeUser = useMappedState((state) => state.user);
  const [isFirstInitial, setIsFirstInitial] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  /* Functions */
  const onSignOut = (): void => {
    reduxUser('postUserSignOut', []);
  };
  const initialize = (): void => {
    setIsFirstInitial(true);
  };
  /* Hooks */
  useDidMount(() => {
    initialize();
  });
  useEffect(() => {
    if (!isFirstInitial) return;
    if (storeUser.userSignOutUrl.url) {
      window.location.href = storeUser.userSignOutUrl.url;
    }
    setIsLoading(false);
  }, [storeUser.userSignOutUrl]);
  /* Main */
  return (
    <div className={classNames(Styles.homeContainer)}>
      <div className={classNames(Styles.homeInfoContainer)}>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h2">使用者名稱</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h3">{storeUser.userAccount.username}</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h2">顯示名稱</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h3">
          {storeUser.userAccount.display_name}
        </Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h2">電子信箱</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h3">{storeUser.userAccount.email}</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h2">允許觸及的 Groups</Typography>
        <Typography className={classNames(Styles.homeInfoItem)} variant="h3">
          {storeUser.userAccount.groups.join('')}
        </Typography>
        <Button variant="contained" color="primary" onClick={onSignOut}>登出</Button>
      </div>
      <Loading typePosition="absolute" typeZIndex={20000} typeIcon="line:fix" isLoading={isLoading} />
    </div>
  );
}
export default memo(Home);
