import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialTiktok
 *
 */
// import { PASS_CORS_KEY } from 'helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
var TIKTOK_URL = 'https://www.tiktok.com';
// const TIKTOK_API_URL: string = 'https://open-api.tiktok.com';
// const PREVENT_CORS_URL: string = 'https://cors.bridged.cc';

export var LoginSocialGithub = function LoginSocialGithub(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'user.info.basic' : _ref$scope,
    client_key = _ref.client_key,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    redirect_uri = _ref.redirect_uri,
    children = _ref.children,
    onResolve = _ref.onResolve,
    onLoginStart = _ref.onLoginStart;
  useEffect(function () {
    var popupWindowURL = new URL(window.location.href);
    var code = popupWindowURL.searchParams.get('code');
    var state = popupWindowURL.searchParams.get('state');
    if (state !== null && state !== void 0 && state.includes('_tiktok') && code) {
      localStorage.setItem('tiktok', code);
      window.close();
    }
  }, []);

  // const getProfile = useCallback(
  //   (data: objectType) => {
  //     fetch(`${PREVENT_CORS_URL}/${TIKTOK_API_URL}/user`, {
  //       method: 'GET',
  //       headers: {
  //         Authorization: `token ${data.access_token}`,
  //         'x-cors-grida-api-key': PASS_CORS_KEY,
  //       },
  //     })
  //       .then(res => res.json())
  //       .then((response: any) => {
  //         onResolve({ provider: 'tiktok', data: { ...response, ...data } });
  //       })
  //       .catch(err => {
  //         onReject(err);
  //       });
  //   },
  //   [onReject, onResolve],
  // );

  // const getAccessToken = useCallback(
  //   (code: string) => {
  //     if (isOnlyGetCode) onResolve({ provider: 'tiktok', data: { code } });
  //     else {
  //       const params = {
  //         code,
  //         client_key,
  //         client_secret,
  //         grant_type: 'authorization_code',
  //       };
  //       const headers = new Headers({
  //         'Content-Type': 'application/x-www-form-urlencoded',
  //         'x-cors-grida-api-key': PASS_CORS_KEY,
  //       });

  //       fetch(`${PREVENT_CORS_URL}/${TIKTOK_API_URL}/oauth/access_token/`, {
  //         method: 'POST',
  //         headers,
  //         body: new URLSearchParams(params),
  //       })
  //         .then(response => response.text())
  //         .then(response => {
  //           console.log(response);
  //           // const data: objectType = {};
  //           // const searchParams: any = new URLSearchParams(response);
  //           // for (const p of searchParams) {
  //           //   data[p[0]] = p[1];
  //           // }
  //           // if (data.access_token) {
  //           //   if (isOnlyGetToken) onResolve({ provider: 'tiktok', data });
  //           //   else getProfile(data);
  //           // } else onReject('no data');
  //         })
  //         .catch(err => {
  //           onReject(err);
  //         });
  //     }
  //   },
  //   [onReject, onResolve, client_key, client_secret, isOnlyGetCode],
  // );

  var handlePostMessage = useCallback(/*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
      var type, code, provider;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            type = _ref2.type, code = _ref2.code, provider = _ref2.provider;
            return _context.abrupt("return", type === 'code' && provider === 'tiktok' && code && onResolve({
              provider: 'tiktok',
              data: {
                code: code
              }
            }));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }(),
  // getAccessToken(code),
  [onResolve]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('tiktok');
    if (code) {
      handlePostMessage({
        provider: 'tiktok',
        type: 'code',
        code: code
      });
      localStorage.removeItem('instagram');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(TIKTOK_URL, "/auth/authorize?client_key=").concat(client_key, "&scope=").concat(scope, "&state=").concat(state + '_tiktok', "&redirect_uri=").concat(redirect_uri, "&response_type=code");
    var width = 450;
    var height = 730;
    var left = window.screen.width / 2 - width / 2;
    var top = window.screen.height / 2 - height / 2;
    window.open(oauthUrl, 'Github', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [scope, state, client_key, redirect_uri, onLoginStart, onChangeLocalStorage]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialGithub);