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

import React, { memo, useCallback, useEffect } from 'react';
var INSTAGRAM_URL = 'https://api.instagram.com';
var INSTAGRAM_API_URL = 'https://graph.instagram.com/';
var PREVENT_CORS_URL = '';
export var LoginSocialInstagram = function LoginSocialInstagram(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    client_id = _ref.client_id,
    client_secret = _ref.client_secret,
    className = _ref.className,
    redirect_uri = _ref.redirect_uri,
    _ref$fields = _ref.fields,
    fields = _ref$fields === void 0 ? 'id,username,account_type,media_count' : _ref$fields,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'user_profile,user_media' : _ref$scope,
    _ref$response_type = _ref.response_type,
    response_type = _ref$response_type === void 0 ? 'code' : _ref$response_type,
    _ref$isOnlyGetCode = _ref.isOnlyGetCode,
    isOnlyGetCode = _ref$isOnlyGetCode === void 0 ? false : _ref$isOnlyGetCode,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    children = _ref.children,
    onReject = _ref.onReject,
    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('_instagram') && code) {
      localStorage.setItem('instagram', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    fetch("".concat(PREVENT_CORS_URL, "/").concat(INSTAGRAM_API_URL, "/me?fields=").concat(fields, "&access_token=").concat(data.access_token), {
      method: 'GET',
      headers: {
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      }
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      onResolve({
        provider: 'instagram',
        data: _extends({}, res, data)
      });
    })["catch"](function (err) {
      onReject(err);
    });
  }, [fields, onReject, onResolve]);
  var getAccessToken = useCallback(function (code) {
    if (isOnlyGetCode) onResolve({
      provider: 'instagram',
      data: {
        code: code
      }
    });else {
      var params = {
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: redirect_uri,
        client_id: client_id,
        client_secret: client_secret
      };
      var headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      });
      fetch("".concat(PREVENT_CORS_URL, "/").concat(INSTAGRAM_URL, "/oauth/access_token"), {
        method: 'POST',
        headers: headers,
        body: new URLSearchParams(params)
      }).then(function (response) {
        return response.json();
      }).then(function (data) {
        if (data.access_token) {
          if (isOnlyGetToken) onResolve({
            provider: 'instagram',
            data: data
          });else getProfile(data);
        } else onReject('no data');
      })["catch"](function (err) {
        onReject(err);
      })["finally"](function () {});
    }
  }, [onReject, onResolve, getProfile, client_id, redirect_uri, client_secret, isOnlyGetCode, isOnlyGetToken]);
  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 === 'instagram' && code && getAccessToken(code));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }(), [getAccessToken]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('instagram');
    if (code) {
      handlePostMessage({
        provider: 'instagram',
        type: 'code',
        code: code
      });
      localStorage.removeItem('instagram');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(INSTAGRAM_URL, "/oauth/authorize?response_type=").concat(response_type, "&client_id=").concat(client_id, "&scope=").concat(scope, "&state=").concat(state + '_instagram', "&redirect_uri=").concat(redirect_uri);
    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, 'Instagram', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [scope, state, client_id, redirect_uri, onLoginStart, response_type, onChangeLocalStorage]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialInstagram);