import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

const SCOPES = [
  'email',
  'pages_show_list',
  'pages_read_engagement',
  'pages_manage_posts',
  'pages_manage_metadata',
  'read_insights',
  'business_management',
].join(',');

function FacebookAuth() {
  const router = useRouter();
  const { cid } = router.query;

  useEffect(() => {
    const code = new URLSearchParams(window.location.hash?.split('#')[1]).get('access_token');

    if (cid) {
      router.replace({
        pathname: 'https://www.facebook.com/v22.0/dialog/oauth',
        query: {
          client_id: cid,
          display: 'popup',
          redirect_uri: `${window.location.origin}/auth/facebook`,
          response_type: 'token',
          scope: SCOPES,
        },
      });
    }

    if (code) {
      window.opener.postMessage({ type: 'ac_auth_fb', code }, '*');
      window.close();
    }
  }, []);

  // eslint-disable-next-line react/jsx-no-useless-fragment
  return <></>;
}

export default FacebookAuth;
