import React, { useEffect } from 'react';
import classNames from 'classnames/bind';

import styles from './SNSLoginCallback.scss';
import Loading from '@src/components/common/Loading';
import APIs from '@src/api/APIs';
import { ESNSType } from '@src/constants/Login';
import { ACCESS_TOKEN } from '@src/constants/Cookie';
import URLInfo from '@src/constants/URLInfo';
import AccessToken from '@src/constants/AccessToken';
import CookieUtil from '@src/utils/CookieUtil';

const cx = classNames.bind(styles);

const SNSLoginCallback: React.FC = () => {
  useEffect(() => {
    const code = new URLSearchParams(location.search).get('code') || '';
    const type = location.pathname.split('/')[2] as ESNSType;

    APIs.signIn(code, type).then((res) => {
      console.log(res);

      if (res) {
        AccessToken.setAccessToken(res);
        CookieUtil.setCookie(ACCESS_TOKEN, res.access_token, CookieUtil.inOneHours);
        window.location.href = URLInfo.HOME;
      }
    }).catch(e => {
      alert('정지된 유저입니다. 다른 아이디로 로그인 시도해주세요.');
      window.location.href = URLInfo.HOME;
    });
  }, []);
  return (
    <div className={cx('callback')}>
      <Loading />
    </div>
  );
};

export default SNSLoginCallback;
