import React from 'react';
import { TextSelection } from '@atlaskit/editor-prosemirror/state';
import { fg } from '@atlaskit/platform-feature-flags';
import { ACTION } from '../../analytics';
import { sendMBEAnalyticsEvent } from './utils';
export const useMultiBodiedExtensionActions = ({
  updateActiveChild,
  editorView,
  getPos,
  node,
  eventDispatcher,
  allowBodiedOverride,
  childrenContainer
}) => {
  const actions = React.useMemo(() => {
    return {
      changeActive(index, options) {
        var _options$selection, _possiblyMbeNode$type;
        const {
          state,
          dispatch
        } = editorView;
        const updateActiveChildResult = updateActiveChild(index);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.CHANGE_ACTIVE, node, eventDispatcher);
        }
        const selection = (_options$selection = options === null || options === void 0 ? void 0 : options.selection) !== null && _options$selection !== void 0 ? _options$selection : 'none';
        if (selection === 'none') {
          return updateActiveChildResult;
        }
        const pos = getPos();
        if (typeof pos !== 'number') {
          return updateActiveChildResult;
        }
        const possiblyMbeNode = state.doc.nodeAt(pos);
        if (possiblyMbeNode && (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$type = possiblyMbeNode.type) === null || _possiblyMbeNode$type === void 0 ? void 0 : _possiblyMbeNode$type.name) === 'multiBodiedExtension' && possiblyMbeNode !== null && possiblyMbeNode !== void 0 && possiblyMbeNode.content) {
          var _possiblyMbeNode$cont;
          if (index < 0 || index >= (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont = possiblyMbeNode.content) === null || _possiblyMbeNode$cont === void 0 ? void 0 : _possiblyMbeNode$cont.childCount)) {
            var _possiblyMbeNode$cont2;
            throw new Error(`Index out of bounds: valid range is 0-${(possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont2 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont2 === void 0 ? void 0 : _possiblyMbeNode$cont2.childCount) - 1} inclusive`);
          }
          let desiredPos = pos;
          for (let i = 0; i < index && i < (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont3 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont3 === void 0 ? void 0 : _possiblyMbeNode$cont3.childCount); i++) {
            var _possiblyMbeNode$cont3, _possiblyMbeNode$cont4, _possiblyMbeNode$cont5;
            desiredPos += (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont4 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont4 === void 0 ? void 0 : (_possiblyMbeNode$cont5 = _possiblyMbeNode$cont4.child(i)) === null || _possiblyMbeNode$cont5 === void 0 ? void 0 : _possiblyMbeNode$cont5.nodeSize) || 0;
          }
          const targetFrame = possiblyMbeNode.content.child(index);
          if (selection === 'start') {
            // +1 moves past the extensionFrame opening token; TextSelection.near() finds
            // the nearest valid text cursor position from there.
            dispatch(state.tr.setSelection(TextSelection.near(state.doc.resolve(desiredPos + 1))));
          } else {
            // Place cursor at the end of the target frame's content.
            // -1 bias searches backward from the frame's closing token.
            dispatch(state.tr.setSelection(TextSelection.near(state.doc.resolve(desiredPos + targetFrame.nodeSize), -1)));
          }
          editorView.focus();
        }
        return updateActiveChildResult;
      },
      addChild() {
        const {
          state,
          dispatch
        } = editorView;
        const p = state.schema.nodes.paragraph.createAndFill({});
        if (!p) {
          throw new Error('Could not create paragraph');
        }
        const frame = state.schema.nodes.extensionFrame.createAndFill({}, [p]);
        const pos = getPos();
        if (typeof pos !== 'number' || !frame) {
          throw new Error('Could not create frame or position not valid');
        }
        const insertAt = Math.min((pos || 1) + node.content.size, state.doc.content.size);
        const tr = state.tr.insert(insertAt, frame);
        tr.setSelection(new TextSelection(tr.doc.resolve(insertAt + 1)));
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.ADD_CHILD, node, eventDispatcher);
        }
        return true;
      },
      getChildrenCount() {
        return node.content.childCount;
      },
      removeChild(index) {
        const pos = getPos();
        // Ignored via go/ees007
        // eslint-disable-next-line @atlaskit/editor/enforce-todo-comment-format
        // TODO: Add child index validation here, don't trust this data
        if (typeof pos !== 'number' || typeof index !== 'number') {
          throw new Error('Position or index not valid');
        }
        const {
          state,
          dispatch
        } = editorView;
        if (node.content.childCount === 1) {
          const tr = state.tr;
          tr.deleteRange(pos, pos + node.content.size);
          dispatch(tr);
          return true;
        }
        const $pos = state.doc.resolve(pos);
        const $startNodePos = state.doc.resolve($pos.start($pos.depth + 1));
        const startFramePosition = $startNodePos.posAtIndex(index);
        const maybeFrameNode = state.doc.nodeAt(startFramePosition);
        if (!maybeFrameNode) {
          throw new Error('Could not find frame node');
        }
        const endFramePosition = maybeFrameNode.content.size + startFramePosition;
        const tr = state.tr;
        tr.deleteRange(startFramePosition, endFramePosition);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.REMOVE_CHILD, node, eventDispatcher);
        }
        return true;
      },
      reorderChildren(fromIndex, toIndex) {
        const pos = getPos();
        if (typeof pos !== 'number' || typeof fromIndex !== 'number' || typeof toIndex !== 'number') {
          throw new Error('Position or index not valid');
        }
        if (fromIndex === toIndex) {
          return true;
        }
        const {
          state,
          dispatch
        } = editorView;

        // Use current node from state (not stale closure)
        const currentNode = state.doc.nodeAt(pos);
        if (!currentNode) {
          throw new Error('Could not find extension node');
        }
        const $pos = state.doc.resolve(pos);
        const $startNodePos = state.doc.resolve($pos.start($pos.depth + 1));

        // Collect all current frame nodes
        const frames = [];
        currentNode.content.forEach(child => {
          frames.push(child);
        });
        if (fromIndex >= frames.length || toIndex >= frames.length) {
          throw new Error('Index out of bounds');
        }

        // Reorder the frames array in memory
        const [removed] = frames.splice(fromIndex, 1);
        frames.splice(toIndex, 0, removed);

        // Atomically replace the entire MBE content with reordered frames
        const tr = state.tr;
        const containerStart = $startNodePos.pos;
        const containerEnd = containerStart + currentNode.content.size;
        tr.replaceWith(containerStart, containerEnd, frames);
        dispatch(tr);
        return true;
      },
      updateParameters(parameters) {
        const {
          state,
          dispatch
        } = editorView;
        const pos = getPos();
        if (typeof pos !== 'number') {
          throw new Error('Position not valid');
        }
        // We are retaining node.attrs to keep the node type and extension key
        // and only updating the parameters coming in from the user
        // parameters will contain only macroParams information
        const updatedParameters = {
          ...node.attrs,
          parameters: {
            ...node.attrs.parameters,
            ...(fg('confluence_frontend_native_tabs_extension') ? {
              ...parameters
            } : {
              macroParams: parameters
            })
          }
        };
        const tr = state.tr.setNodeMarkup(pos, null, updatedParameters);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.UPDATE_PARAMETERS, node, eventDispatcher);
        }
        return true;
      },
      getChildren() {
        var _state$doc$nodeAt;
        const {
          state
        } = editorView;
        const pos = getPos();
        if (typeof pos !== 'number') {
          return [];
        }
        const children = (_state$doc$nodeAt = state.doc.nodeAt(pos)) === null || _state$doc$nodeAt === void 0 ? void 0 : _state$doc$nodeAt.content;
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.GET_CHILDREN, node, eventDispatcher);
        }
        return children ? children.toJSON() : [];
      },
      getChildrenContainer() {
        if (!allowBodiedOverride) {
          throw new Error('Could not provide children container');
        }
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.GET_CHILDREN_CONTAINER, node, eventDispatcher);
        }
        return childrenContainer;
      }
    };
  }, [node, editorView, getPos, updateActiveChild, eventDispatcher, allowBodiedOverride, childrenContainer]);
  return actions;
};