import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _extends from "@babel/runtime/helpers/esm/extends";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable no-unused-vars */
/* eslint-disable camelcase */
/**
 *
 * LoginSocialTwitter
 *
 */
// import { PASS_CORS_KEY } from 'helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
var TWITTER_URL = 'https://twitter.com';
var TWITTER_API_URL = 'https://api.twitter.com';
var PREVENT_CORS_URL = '';
export var LoginSocialTwitter = function LoginSocialTwitter(_ref) {
  var client_id = _ref.client_id,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    redirect_uri = _ref.redirect_uri,
    children = _ref.children,
    _ref$fields = _ref.fields,
    fields = _ref$fields === void 0 ? 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld' : _ref$fields,
    _ref$state = _ref.state,
    state = _ref$state === void 0 ? 'state' : _ref$state,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'users.read%20tweet.read' : _ref$scope,
    _ref$isOnlyGetCode = _ref.isOnlyGetCode,
    isOnlyGetCode = _ref$isOnlyGetCode === void 0 ? false : _ref$isOnlyGetCode,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    onLoginStart = _ref.onLoginStart,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve;
  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('_twitter') && code) {
      localStorage.setItem('twitter', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    var url = "".concat(PREVENT_CORS_URL, "/").concat(TWITTER_API_URL, "/2/users/me?user.fields=").concat(fields);
    fetch(url, {
      method: 'GET',
      headers: {
        Authorization: "Bearer ".concat(data.access_token)
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      }
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      onResolve({
        provider: 'twitter',
        data: _extends({}, data, res.data)
      });
    })["catch"](function (err) {
      return onReject(err);
    });
  }, [fields, onReject, onResolve]);
  var getAccessToken = useCallback(/*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(code) {
      var details, requestOAuthURL, data;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (!isOnlyGetCode) {
              _context.next = 1;
              break;
            }
            onResolve({
              provider: 'twitter',
              data: {
                code: code
              }
            });
            _context.next = 3;
            break;
          case 1:
            details = new URLSearchParams({
              code: code,
              redirect_uri: redirect_uri,
              client_id: client_id,
              grant_type: "authorization_code",
              code_verifier: 'challenge'
            });
            requestOAuthURL = "".concat(PREVENT_CORS_URL, "/").concat(TWITTER_API_URL, "/2/oauth2/token");
            _context.next = 2;
            return fetch(requestOAuthURL, {
              method: 'POST',
              body: details,
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
                // 'x-cors-grida-api-key': PASS_CORS_KEY,
              }
            }).then(function (data) {
              return data.json();
            })["catch"](function (err) {
              return onReject(err);
            });
          case 2:
            data = _context.sent;
            if (data.access_token) {
              if (isOnlyGetToken) onResolve({
                provider: 'twitter',
                data: data
              });else getProfile(data);
            }
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }(), [onReject, getProfile, onResolve, client_id, redirect_uri, isOnlyGetCode, isOnlyGetToken]);
  var handlePostMessage = useCallback(/*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3) {
      var type, code, provider;
      return _regeneratorRuntime.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            type = _ref3.type, code = _ref3.code, provider = _ref3.provider;
            return _context2.abrupt("return", type === 'code' && provider === 'twitter' && code && getAccessToken(code));
          case 1:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function (_x2) {
      return _ref4.apply(this, arguments);
    };
  }(), [getAccessToken]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('twitter');
    if (code) {
      handlePostMessage({
        provider: 'twitter',
        type: 'code',
        code: code
      });
      localStorage.removeItem('twitter');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
    var oauthUrl, width, height, left, top;
    return _regeneratorRuntime.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          onLoginStart && onLoginStart();
          window.addEventListener('storage', onChangeLocalStorage, false);
          oauthUrl = "".concat(TWITTER_URL, "/i/oauth2/authorize?response_type=code&client_id=").concat(client_id, "&redirect_uri=").concat(redirect_uri, "&scope=").concat(scope, "&state=").concat(state + '_twitter', "&code_challenge=challenge&code_challenge_method=plain");
          width = 450;
          height = 730;
          left = window.screen.width / 2 - width / 2;
          top = window.screen.height / 2 - height / 2;
          window.open(oauthUrl, 'twitter', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
        case 1:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  })), [scope, state, client_id, onLoginStart, redirect_uri, onChangeLocalStorage]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialTwitter);