import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback, useMemo, useRef } from 'react';
import { extractSmartLinkProvider } from '@atlaskit/link-extractors';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { ACTION_RESOLVING, ACTION_UPDATE_METADATA_STATUS, cardAction } from '@atlaskit/linking-common';
import { auth } from '@atlaskit/outbound-auth-flow-client';
import { fg } from '@atlaskit/platform-feature-flags';
import { functionWithFG } from '@atlaskit/platform-feature-flags-react';
import { ROVO_POST_MESSAGE_EVENT_TYPE } from '@atlaskit/rovo-triggers/post-message-to-pubsub';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { SmartLinkStatus } from '../../constants';
import { noop } from '../../utils';
import { getIsRovoChatEnabled } from '../../utils/rovo';
import { startUfoExperience } from '../analytics';
import { getByDefinitionId, getDefinitionId, getExtensionKey, getServices } from '../helpers';
import useActionFlags from '../hooks/use-action-flags';
import useInvokeClientAction from '../hooks/use-invoke-client-action';
import useResolve from '../hooks/use-resolve';
var POST_AUTH_CHAT_EXTENSION_KEY = 'google-object-provider';
var SMART_LINK_TO_ROVO_SOURCE = 'smart-link';
var getPostAuthChatPayloadId = function getPostAuthChatPayloadId() {
  if (typeof crypto !== 'undefined') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID();
    }
    if (typeof crypto.getRandomValues === 'function') {
      var values = new Uint32Array(4);
      crypto.getRandomValues(values);
      return "smart-link-post-auth-chat-".concat(Array.from(values, function (value) {
        return value.toString(16);
      }).join('-'));
    }
  }
  return "smart-link-post-auth-chat-".concat(Date.now());
};
var sendPostAuthChatOpenMessage = function sendPostAuthChatOpenMessage(url) {
  var _window$parent;
  if (typeof window === 'undefined' || typeof ((_window$parent = window.parent) === null || _window$parent === void 0 ? void 0 : _window$parent.postMessage) !== 'function') {
    return;
  }
  var payload = {
    type: 'chat-new',
    source: SMART_LINK_TO_ROVO_SOURCE,
    data: {
      dialogues: [],
      mode: {
        useCurrentPageContext: false
      },
      aiFeatureContext: {
        projectContext: {
          projectId: url,
          // Use the URL as projectName to avoid introducing a hardcoded
          // user-facing provider label in Smart Card.
          projectName: url,
          projectUrl: url
        }
      }
    },
    openChat: true,
    openChatMode: 'mini-modal'
  };
  window.parent.postMessage({
    eventType: ROVO_POST_MESSAGE_EVENT_TYPE,
    payload: payload,
    payloadId: getPostAuthChatPayloadId()
  }, '*');
};
export var useSmartCardActions = function useSmartCardActions(id, url) {
  var resolveUrl = useResolve();
  var invokeClientAction = useInvokeClientAction({});
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  var useActionFlagsGated = functionWithFG('platform_sl_connect_account_flag', useActionFlags, noop);
  var flags = useActionFlagsGated();
  var _useSmartLinkContext = useSmartLinkContext(),
    store = _useSmartLinkContext.store,
    rovoOptions = _useSmartLinkContext.rovoOptions;
  var rovoOptionsRef = useRef(rovoOptions);
  rovoOptionsRef.current = rovoOptions;
  var getState = store.getState,
    dispatch = store.dispatch;
  var getSmartLinkState = useCallback(function () {
    var _getState$url;
    var _ref = (_getState$url = getState()[url]) !== null && _getState$url !== void 0 ? _getState$url : {
        status: SmartLinkStatus.Pending
      },
      details = _ref.details,
      status = _ref.status,
      metadataStatus = _ref.metadataStatus;
    return {
      details: details,
      status: status,
      metadataStatus: metadataStatus
    };
  }, [getState, url]);
  var setMetadataStatus = useCallback(function (metadataStatus) {
    dispatch(cardAction(ACTION_UPDATE_METADATA_STATUS, {
      url: url
    }, undefined, undefined, metadataStatus));
  }, [dispatch, url]);
  var resolve = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var resourceUrl,
      isReloading,
      isMetadataRequest,
      _args = arguments;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          resourceUrl = _args.length > 0 && _args[0] !== undefined ? _args[0] : url;
          isReloading = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
          isMetadataRequest = _args.length > 2 && _args[2] !== undefined ? _args[2] : false;
          return _context.abrupt("return", resolveUrl(resourceUrl, isReloading, isMetadataRequest, id));
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })), [id, resolveUrl, url]);
  var register = useCallback(function () {
    var _getSmartLinkState = getSmartLinkState(),
      details = _getSmartLinkState.details;
    if (!details) {
      dispatch(cardAction(ACTION_RESOLVING, {
        url: url
      }));
      setMetadataStatus('pending');
    }
    return resolve();
  }, [getSmartLinkState, resolve, dispatch, url, setMetadataStatus]);
  var reload = useCallback(function () {
    var _getSmartLinkState2 = getSmartLinkState(),
      details = _getSmartLinkState2.details;
    var definitionId = getDefinitionId(details);
    if (definitionId) {
      getByDefinitionId(definitionId, getState()).map(function (url) {
        return resolve(url, true);
      });
    } else {
      resolve(url, true);
    }
  }, [getSmartLinkState, url, getState, resolve]);
  var loadMetadata = useCallback(function () {
    var _getSmartLinkState3 = getSmartLinkState(),
      metadataStatus = _getSmartLinkState3.metadataStatus;
    //metadataStatus will be undefined for SSR links only
    if (metadataStatus === undefined) {
      setMetadataStatus('pending');
      return resolve(url, false, true);
    }
  }, [getSmartLinkState, resolve, setMetadataStatus, url]);
  var authorize = useCallback(function (appearance) {
    var _getSmartLinkState4 = getSmartLinkState(),
      details = _getSmartLinkState4.details,
      status = _getSmartLinkState4.status;
    var definitionId = getDefinitionId(details);
    var extensionKey = getExtensionKey(details);
    var isSupportedPostAuthChatExtensionKey = extensionKey === POST_AUTH_CHAT_EXTENSION_KEY;
    var services = getServices(details);
    // When authentication is triggered, let GAS know!
    if (status === 'unauthorized') {
      fireEvent('ui.button.clicked.connectAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (status === 'forbidden') {
      fireEvent('ui.smartLink.clicked.tryAnotherAccount', {
        display: appearance,
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
    }
    if (services.length > 0) {
      fireEvent('screen.consentModal.viewed', {
        definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
      });
      auth(services[0].url).then(function () {
        fireEvent('track.applicationAccount.connected', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });
        startUfoExperience('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: 'success'
        });
        fireEvent('operational.smartLink.connectSucceeded', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
        });

        // Post-auth Chat onboarding: auto-open Rovo Chat mini-modal with the
        // authed 3P link as context, for supported providers (e.g. Google Drive).
        // Provider eligibility is derived from the pre-auth SmartLink state.
        var isEligibleForPostAuthChat = status === 'unauthorized' && isSupportedPostAuthChatExtensionKey && fg('platform_sl_3p_post_auth_chat_open_fg') && getIsRovoChatEnabled(rovoOptionsRef.current);

        // Experiment check: fires exposure for both control and treatment.
        // Only reached after eligibility preconditions + kill switch pass, so
        // exposure is counted for the triggered eligible pool.
        var isPostAuthChatTreatment = isEligibleForPostAuthChat && expValEquals('platform_sl_3p_post_auth_chat_open_exp', 'isEnabled', true);
        if (status === 'unauthorized' && !isPostAuthChatTreatment) {
          if (fg('platform_sl_connect_account_flag')) {
            var provider = extractSmartLinkProvider(details);
            flags === null || flags === void 0 || flags.showConnectFlag({
              id: "smart-link-connect-success-".concat(extensionKey),
              provider: provider
            });
          }
        }
        reload();
        if (isPostAuthChatTreatment) {
          sendPostAuthChatOpenMessage(url);
        }
      }, function (err) {
        var _err$type;
        startUfoExperience('smart-link-authenticated', id, {
          extensionKey: extensionKey,
          status: err.type
        });
        fireEvent('operational.smartLink.connectFailed', {
          definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null,
          reason: (_err$type = err.type) !== null && _err$type !== void 0 ? _err$type : null
        });
        if (err.type === 'auth_window_closed') {
          fireEvent('ui.consentModal.closed', {
            display: appearance,
            definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
          });
        }
        reload();
      });
    }
  }, [getSmartLinkState, id, reload, fireEvent, flags, url]);
  var invoke = useCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(opts, appearance) {
      var key, action, source;
      return _regeneratorRuntime.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            key = opts.key, action = opts.action;
            source = opts.source || appearance;
            if (!(opts.type === 'client')) {
              _context2.next = 2;
              break;
            }
            _context2.next = 1;
            return invokeClientAction({
              actionFn: opts.action.promise,
              actionType: action.type,
              display: source,
              extensionKey: key
            });
          case 1:
            return _context2.abrupt("return", _context2.sent);
          case 2:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function (_x, _x2) {
      return _ref3.apply(this, arguments);
    };
  }(), [invokeClientAction]);
  return useMemo(function () {
    return {
      register: register,
      reload: reload,
      authorize: authorize,
      invoke: invoke,
      loadMetadata: loadMetadata
    };
  }, [register, reload, authorize, invoke, loadMetadata]);
};