import _extends from "@babel/runtime/helpers/esm/extends";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialAmazon
 *
 */
/* "use client" */

import React, { memo, useEffect, useState, useCallback, useRef } from 'react';
var JS_SRC = 'https://assets.loginwithamazon.com/sdk/na/login1.js';
var SCRIPT_ID = 'amazon-login';
var _window = global.window;
export var LoginSocialAmazon = function LoginSocialAmazon(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    client_id = _ref.client_id,
    className = _ref.className,
    redirect_uri = _ref.redirect_uri,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'profile' : _ref$scope,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    onlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    _ref$scope_data = _ref.scope_data,
    scope_data = _ref$scope_data === void 0 ? {
      profile: {
        essential: true
      }
    } : _ref$scope_data,
    _ref$response_type = _ref.response_type,
    response_type = _ref$response_type === void 0 ? 'token' : _ref$response_type,
    children = _ref.children,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve,
    onLoginStart = _ref.onLoginStart;
  var scriptNodeRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSdkLoaded = _useState2[0],
    setIsSdkLoaded = _useState2[1];
  useEffect(function () {
    !isSdkLoaded && load();
  }, [isSdkLoaded]);
  useEffect(function () {
    return function () {
      if (scriptNodeRef.current) scriptNodeRef.current.remove();
    };
  }, []);
  var checkIsExistsSDKScript = useCallback(function () {
    return !!document.getElementById(SCRIPT_ID);
  }, []);
  var insertScriptGoogle = useCallback(function (d) {
    var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'script';
    var id = arguments.length > 2 ? arguments[2] : undefined;
    var jsSrc = arguments.length > 3 ? arguments[3] : undefined;
    var cb = arguments.length > 4 ? arguments[4] : undefined;
    var ggScriptTag = d.createElement(s);
    ggScriptTag.id = id;
    ggScriptTag.src = jsSrc;
    ggScriptTag.async = true;
    ggScriptTag.defer = true;
    var scriptNode = document.getElementsByTagName('script')[0];
    scriptNodeRef.current = ggScriptTag;
    scriptNode && scriptNode.parentNode && scriptNode.parentNode.insertBefore(ggScriptTag, scriptNode);
    ggScriptTag.onload = cb;
  }, []);
  var getUserInfo = useCallback(/*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(res) {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            fetch("https://api.amazon.com/user/profile", {
              headers: {
                Authorization: "Bearer ".concat(res.access_token)
              }
            }).then(function (data) {
              return data.json();
            }).then(function (data) {
              onResolve({
                provider: 'amazon',
                data: _extends({}, data, res)
              });
            })["catch"](function (err) {
              onReject(err);
            })["finally"](function () {});
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }(), [onReject, onResolve]);
  var handleResponse = useCallback(function (res) {
    if (onlyGetToken) onResolve({
      provider: 'amazon',
      data: _extends({}, res)
    });else getUserInfo(res);
  }, [getUserInfo, onResolve, onlyGetToken]);
  var handleError = useCallback(function (err) {
    onReject(err);
  }, [onReject]);
  var load = useCallback(function () {
    if (checkIsExistsSDKScript()) {
      setIsSdkLoaded(true);
    } else {
      insertScriptGoogle(document, 'script', SCRIPT_ID, JS_SRC, function () {
        _window.amazon.Login.setClientId(client_id);
        setIsSdkLoaded(true);
      });
    }
  }, [checkIsExistsSDKScript, client_id, insertScriptGoogle]);
  var onLogin = useCallback(function () {
    if (!isSdkLoaded) return;
    if (!_window.amazon) {
      load();
      onReject("Google SDK isn't loaded!");
    } else {
      onLoginStart && onLoginStart();
      _window.amazon.Login.authorize({
        scope: scope,
        scope_data: scope_data,
        response_type: response_type,
        redirect_uri: redirect_uri,
        state: state
      }, function (res) {
        if (res.error) handleError(res.error);else handleResponse(res);
      });
    }
  }, [load, scope, state, onReject, scope_data, isSdkLoaded, handleError, onLoginStart, redirect_uri, response_type, handleResponse]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialAmazon);