import _extends from "@babel/runtime/helpers/extends";
import React, { useCallback, useState } from 'react';
import { useAnalyticsEvents } from '../../../../../../common/analytics/generated/use-analytics-events';
import useInvoke from '../../../../../../state/hooks/use-invoke';
import { getInvokeFailureReason } from '../../../../../../state/hooks/use-invoke/utils';
import useResolve from '../../../../../../state/hooks/use-resolve';
import createInvokeRequest from '../../../../../../utils/actions/create-invoke-request';
import Action from '../index';
const ServerAction = ({
  action,
  onClick,
  onError: onErrorCallback,
  ...props
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const invoke = useInvoke();
  const reload = useResolve();
  const {
    fireEvent
  } = useAnalyticsEvents();
  const handleClick = useCallback(async () => {
    if (action) {
      var _action$action;
      const smartLinkActionType = (_action$action = action.action) === null || _action$action === void 0 ? void 0 : _action$action.actionType;
      try {
        setIsLoading(true);
        if (smartLinkActionType === 'FollowEntityAction' || smartLinkActionType === 'UnfollowEntityAction') {
          fireEvent('ui.button.clicked.smartLinkFollowButton', {});
        } else {
          fireEvent(`ui.button.clicked.${smartLinkActionType}`, {});
        }
        fireEvent('track.smartLinkQuickAction.started', {
          smartLinkActionType
        });
        const request = createInvokeRequest(action);
        await invoke(request);
        fireEvent('track.smartLinkQuickAction.success', {
          smartLinkActionType
        });
        if (action.reload && action.reload.url) {
          await reload({
            url: action.reload.url,
            isReloading: true,
            id: action.reload.id
          });
        }
        setIsLoading(false);
        if (onClick) {
          onClick();
        }
      } catch (err) {
        setIsLoading(false);
        fireEvent('track.smartLinkQuickAction.failed', {
          smartLinkActionType,
          reason: getInvokeFailureReason(err)
        });
        onErrorCallback === null || onErrorCallback === void 0 ? void 0 : onErrorCallback();
      }
    }
  }, [action, invoke, onClick, onErrorCallback, reload, fireEvent]);
  return /*#__PURE__*/React.createElement(Action, _extends({}, props, {
    isLoading: isLoading,
    onClick: handleClick
  }));
};
export default ServerAction;