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

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

  useEffect(() => {
    if (clientId) {
      router.replace({
        pathname: 'https://zoom.us/oauth/authorize',
        query: {
          state: new URLSearchParams({
            state,
            redirectUri,
          }).toString,
          response_type: 'code',
          client_id: clientId,
          redirect_uri: `${window.location.origin}/auth/zoom`,
        },
      });
    }

    if (code) {
      const stateParams = new URLSearchParams(decodeURIComponent(state));

      router.replace({
        pathname: stateParams.get('redirectUri'),
        query: {
          code,
          state: stateParams.get('state'),
        },
      });
    }
  }, []);

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

export default ZoomAuth;
