import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialGoogle
 *
 */
// import { PASS_CORS_KEY } from 'helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
// const SCOPE = ''
// const JS_SRC = 'https://apis.google.com/js/api.js'
var JS_SRC = 'https://accounts.google.com/gsi/client';
var SCRIPT_ID = 'google-login';
var PREVENT_CORS_URL = '';
var _window = globalThis.window;
var LoginSocialGoogle = function LoginSocialGoogle(_ref) {
  var client_id = _ref.client_id,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'https://www.googleapis.com/auth/userinfo.profile' : _ref$scope,
    _ref$prompt = _ref.prompt,
    prompt = _ref$prompt === void 0 ? 'select_account' : _ref$prompt,
    _ref$typeResponse = _ref.typeResponse,
    typeResponse = _ref$typeResponse === void 0 ? 'accessToken' : _ref$typeResponse,
    ux_mode = _ref.ux_mode,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    _ref$login_hint = _ref.login_hint,
    login_hint = _ref$login_hint === void 0 ? '' : _ref$login_hint,
    _ref$access_type = _ref.access_type,
    access_type = _ref$access_type === void 0 ? 'online' : _ref$access_type,
    onLoginStart = _ref.onLoginStart,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve,
    _ref$redirect_uri = _ref.redirect_uri,
    redirect_uri = _ref$redirect_uri === void 0 ? '/' : _ref$redirect_uri,
    _ref$auto_select = _ref.auto_select,
    auto_select = _ref$auto_select === void 0 ? false : _ref$auto_select,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    _ref$cookie_policy = _ref.cookie_policy,
    cookie_policy = _ref$cookie_policy === void 0 ? 'single_host_origin' : _ref$cookie_policy,
    _ref$hosted_domain = _ref.hosted_domain,
    hosted_domain = _ref$hosted_domain === void 0 ? '' : _ref$hosted_domain,
    _ref$discoveryDocs = _ref.discoveryDocs,
    discoveryDocs = _ref$discoveryDocs === void 0 ? '' : _ref$discoveryDocs,
    children = _ref.children,
    _ref$fetch_basic_prof = _ref.fetch_basic_profile,
    fetch_basic_profile = _ref$fetch_basic_prof === void 0 ? true : _ref$fetch_basic_prof;
  var scriptNodeRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSdkLoaded = _useState2[0],
    setIsSdkLoaded = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    instance = _useState4[0],
    setInstance = _useState4[1];
  useEffect(function () {
    !isSdkLoaded && load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [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 onGetMe = useCallback(function (res) {
    if (typeResponse === 'accessToken') {
      var headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
        Authorization: 'Bearer ' + res.access_token
      });
      fetch("".concat(PREVENT_CORS_URL, "/https://www.googleapis.com/oauth2/v3/userinfo?alt=json"), {
        method: 'GET',
        headers: headers
      }).then(function (response) {
        return response.json();
      }).then(function (response) {
        var data = _extends({}, res, response);
        onResolve({
          provider: 'google',
          data: data
        });
      })["catch"](function (err) {
        onReject(err);
      });
    } else {
      fetch("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=".concat(res.credential), {
        method: 'GET'
      }).then(function (response) {
        return response.json();
      }).then(function (response) {
        var data = _extends({}, res, response);
        onResolve({
          provider: 'google',
          data: data
        });
      })["catch"](function (err) {
        onReject(err);
      });
    }
  }, [typeResponse, onReject, onResolve]);
  var handleResponse = useCallback(function (res) {
    if (res && access_type === 'offline') onResolve({
      provider: 'google',
      data: res
    });else {
      if (res !== null && res !== void 0 && res.access_token) {
        if (isOnlyGetToken) onResolve({
          provider: 'google',
          data: res
        });else onGetMe(res);
      } else {
        var data = res;
        if (isOnlyGetToken) onResolve({
          provider: 'google',
          data: data
        });else onGetMe(res);
      }
    }
  }, [access_type, isOnlyGetToken, onGetMe, onResolve]);
  var handleError = useCallback(function (res) {
    onReject({
      provider: 'google',
      data: res
    });
  }, [onReject]);
  var load = useCallback(function () {
    if (checkIsExistsSDKScript()) {
      setIsSdkLoaded(true);
    } else {
      insertScriptGoogle(document, 'script', SCRIPT_ID, JS_SRC, function () {
        var params = {
          client_id: client_id,
          ux_mode: ux_mode
        };
        var client = null;
        if (typeResponse === 'idToken') {
          _window.google.accounts.id.initialize(_extends({}, params, {
            auto_select: auto_select,
            prompt: 'select_account',
            login_uri: redirect_uri,
            callback: handleResponse,
            native_callback: handleResponse,
            error_callback: handleError
          }));
        } else {
          var payload = _extends({}, params, {
            scope: scope,
            prompt: prompt,
            login_hint: login_hint,
            access_type: access_type,
            hosted_domain: hosted_domain,
            redirect_uri: redirect_uri,
            cookie_policy: cookie_policy,
            discoveryDocs: discoveryDocs,
            immediate: true,
            fetch_basic_profile: fetch_basic_profile,
            callback: handleResponse,
            error_callback: handleError
          });
          if (access_type === 'offline') client = _window.google.accounts.oauth2.initCodeClient(payload);else client = _window.google.accounts.oauth2.initTokenClient(payload);
        }
        if (client) setInstance(client);
        setIsSdkLoaded(true);
      });
    }
  }, [scope, prompt, ux_mode, client_id, login_hint, auto_select, access_type, redirect_uri, typeResponse, discoveryDocs, cookie_policy, hosted_domain, handleResponse, handleError, fetch_basic_profile, insertScriptGoogle, checkIsExistsSDKScript]);
  var loginGoogle = useCallback(function () {
    if (!isSdkLoaded) return;
    if (!_window.google) {
      load();
      onReject("Google SDK isn't loaded!");
    } else {
      onLoginStart && onLoginStart();
      if (instance) access_type === 'offline' ? instance.requestCode() : instance.requestAccessToken();else _window.google.accounts.id.prompt();
    }
  }, [access_type, instance, isSdkLoaded, load, onLoginStart, onReject]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: loginGoogle
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialGoogle);