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

import {
  OAUTH_RESPONSE_WITH_CODE,
  OAUTH_RESPONSE_WITH_ERROR,
} from '@/modules/feeds/Editor/components/FormElements/Authorization/constants';

function TiktokAuth() {
  const router = useRouter();
  const { clientId, code, error } = router.query;

  useEffect(() => {
    if (clientId) {
      router.replace({
        pathname: 'https://www.tiktok.com/v2/auth/authorize',
        query: {
          client_key: clientId,
          redirect_uri: `${window.location.origin}/auth/tiktok`,
          //redirect_uri: `https://tt.test/auth/tiktok`,
          response_type: 'code',
          scope: 'user.info.basic,video.list',
        },
      });
    }
  }, [clientId]);

  useEffect(() => {
    if (code || error) {
      const payload = code || error;
      const type = code ? OAUTH_RESPONSE_WITH_CODE : OAUTH_RESPONSE_WITH_ERROR;
      window.opener.postMessage({ type, payload }, '*');
      window.close();
    }
  }, [code, error]);

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

export default TiktokAuth;
