import _extends from "@babel/runtime/helpers/extends";
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { AnalyticsContext } from '@atlaskit/analytics-next';
import { LinkPicker } from '@atlaskit/link-picker';
import { getAnalyticsEditorAppearance } from '../../../utils';
import { useEscapeClickaway } from './useEscapeClickaway';

/**
 * Returns a type that matches T but where keys (K) are now optional
 */

export const EditorLinkPicker = ({
  view,
  onCancel,
  invokeMethod = '_unknown',
  editorAppearance,
  onClose,
  onEscapeCallback,
  onClickAwayCallback,
  ...restProps
}) => {
  /**
   * Track onClose handler in a
   * ref so that we void needing it in the dependency array
   * below
   */
  const onCloseRef = useRef(onClose);
  useEffect(() => {
    onCloseRef.current = onClose;
  });

  /**
   * Call onClose on mount, usefull to provide
   * a handler for performing an action after the component has been
   * unmounted (e.g. return focus to the editors)
   */
  useEffect(() => () => {
    var _onCloseRef$current;
    return (_onCloseRef$current = onCloseRef.current) === null || _onCloseRef$current === void 0 ? void 0 : _onCloseRef$current.call(onCloseRef);
  }, []);
  const onEscape = useCallback(() => {
    const {
      state,
      dispatch
    } = view;
    onEscapeCallback === null || onEscapeCallback === void 0 ? void 0 : onEscapeCallback(state, dispatch);
    onCancel === null || onCancel === void 0 ? void 0 : onCancel();
  }, [view, onCancel, onEscapeCallback]);
  const onClickAway = useCallback(() => {
    const {
      state,
      dispatch
    } = view;
    onClickAwayCallback === null || onClickAwayCallback === void 0 ? void 0 : onClickAwayCallback(state, dispatch);
    onCancel === null || onCancel === void 0 ? void 0 : onCancel();
  }, [view, onCancel, onClickAwayCallback]);
  const ref = useEscapeClickaway(onEscape, onClickAway);
  const analyticsEditorAppearance = getAnalyticsEditorAppearance(editorAppearance);
  const analyticsData = useMemo(() => ({
    attributes: {
      invokeMethod,
      location: analyticsEditorAppearance
    },
    // Below is added for the future implementation of Linking Platform namespaced analytic context
    location: analyticsEditorAppearance
  }), [invokeMethod, analyticsEditorAppearance]);
  return /*#__PURE__*/React.createElement("div", {
    ref: ref
  }, /*#__PURE__*/React.createElement(AnalyticsContext, {
    data: analyticsData
  }, /*#__PURE__*/React.createElement(LinkPicker, _extends({}, restProps, {
    onCancel: onEscape
  }))));
};