import { useDispatch, useSelector } from 'react-redux';
import { resetProfile } from '@src/store/reducers/UserReducer';
import AccessToken from '@src/constants/AccessToken';
import { ACCESS_TOKEN } from '@src/constants/Cookie';
import URLInfo from '@src/constants/URLInfo';
import { useHistory } from 'react-router';
import CookieUtil from '@src/utils/CookieUtil';

const useLogin = () => {
  const history = useHistory();
  const dispatch = useDispatch();
  const { userInfo } = useSelector(store => store.user);
  const isLogin = !!userInfo;
  const loginText = isLogin ? '로그아웃' : '로그인';

  const handleClickLogin = () => {
    window.location.href = URLInfo.LOGIN;
  };

  const handleClickLogout = () => {
    AccessToken.setAccessToken('');
    CookieUtil.setCookie(ACCESS_TOKEN, '', CookieUtil.inOneHours);
    dispatch(resetProfile());
    history.push(URLInfo.HOME);
  };

  const handleClickLoginButton = () => {
    if (isLogin) {
      handleClickLogout();
    } else {
      handleClickLogin();
    }
  };

  const checkLogin = (): boolean => {
    if (!isLogin) {
      const result = confirm('로그인이 필요합니다. 로그인 하시겠습니까?');

      if (result) {
        window.location.href = URLInfo.LOGIN;
      }

      return false;;
    }

    return true;
  };

  return {
    isLogin,
    loginText,
    handleClickLogin,
    handleClickLogout,
    handleClickLoginButton,
    checkLogin
  };
};

export default useLogin;
