import React, { useEffect } from 'react';
import { useRouter } from 'next/router';
import { PublicClientApplication } from '@azure/msal-browser';

const SCOPES = {
  teams: ['User.Read', 'UserNotification.ReadWrite.CreatedByApp'],
  sharepoint: ['User.Read'],
};

function TeamsAuth() {
  const router = useRouter();
  const { authService, clientId, redirectUri, state } = router.query;

  const msalConfig = {
    auth: {
      clientId,
      authority: 'https://login.microsoftonline.com/organizations',
      validateAuthority: false,
      navigateToLoginRequestUrl: false,
      redirectUri: `${window.location.origin}/auth/${authService}`,
    },
    cache: {
      cacheLocation: 'sessionStorage',
      storeAuthStateInCookie: false,
    },
    system: {
      allowRedirectInIframe: true,
      navigateFrameWait: 60000,
      windowHashTimeout: 60000,
      iframeHashTimeout: 60000,
      loadFrameTimeout: 60000,
    },
  };

  const msalInstance = new PublicClientApplication(msalConfig);

  useEffect(() => {
    if (clientId) {
      msalInstance.loginRedirect({
        scopes: SCOPES[authService],
        state: new URLSearchParams({
          state,
          redirectUri,
        }).toString,
      });
    } else {
      const paramsFromMSHash = new URLSearchParams(window.location.hash?.split('#')[1]);

      const {
        code,
        state: stateFromMSHash,
        client_info: clientInfo,
        session_state: sessionState,
      } = Object.fromEntries(paramsFromMSHash);

      const stateParams = new URLSearchParams(decodeURIComponent(stateFromMSHash));

      router.replace({
        pathname: stateParams.get('redirectUri'),
        hash: `code=${code}&client_info=${clientInfo}&session_state=${sessionState}&state=${stateParams.get('state')}`,
      });
    }
  }, []);

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

export default TeamsAuth;
