import { useLayoutEffect, useMemo, useRef } from 'react';
import debounce from 'lodash/debounce';

// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any

/**
 *
 * Directly map object values
 *
 * @param object The object to transform
 * @param mapFunction The function to map an old value to new one
 * @returns Object with the same key but transformed values
 *
 */
function mapValues(object, mapFunction) {
  return Object.entries(object).reduce((acc, [key, value]) => ({
    ...acc,
    [key]: mapFunction(value)
  }), {});
}

// When we use the `useSharedPluginState` example: `useSharedPluginState(api, ['width'])`
// it will re-render every time the component re-renders as the array "['width']" is seen as an update.
// This hook is used to prevent re-renders due to this.
function useStaticPlugins(plugins) {
  // eslint-disable-next-line react-hooks/exhaustive-deps
  return useMemo(() => plugins, []);
}
/**
 *
 * ⚠️⚠️⚠️ This is a debounced hook ⚠️⚠️⚠️
 * If the plugins you are listening to generate multiple shared states while the user is typing,
 * your React Component will get only the last one.
 *
 * Used to run effects on changes in editor state - similar to `useSharedPluginState` except this
 * is for reacting to state changes so does not cause re-renders. The effect callback passed will be called
 * on initialisation and when the state changes (with the latest callback we are provided).
 *
 * Example in plugin:
 *
 * ```typescript
 * function ExampleContent({ api }: Props) {
 *   const pluginStateCallback = useCallback(( { dogState, exampleState } ) => {
 *       // Use as necessary ie. fire analytics or network requests
 *       console.log(dogState, exampleState)
 *   }, [])
 *   usePluginStateEffect(
 *     api,
 *     ['dog', 'example'],
 *     pluginStateCallback
 *   )
 *   return <p>Content</p>
 * }
 *
 * const examplePlugin: NextEditorPlugin<'example', { dependencies: [typeof pluginDog] }> = ({ api }) => {
 *   return {
 *     name: 'example',
 *     contentComponent: () =>
 *       <ExampleContent
 *         api={api}
 *         />
 *   }
 * }
 * ```
 *
 * @param injectionApi Plugin injection API from `NextEditorPlugin`
 * @param plugins Plugin names to get the shared plugin state for
 * @param effect A callback, the parameter is a corresponding object, the keys are names of the plugin with `State` appended,
 * the values are the shared state exposed by that plugin. This effect fires when the state changes and runs the most recent callback passed.
 * If the callback changes the effect is not re-run - it is still recommended however to wrap your effect in `useCallback`,
 * You can return a function from your effect to call any cleanup activities which will be called on unmount and when `editorApi` changes.
 */
export function usePluginStateEffect(injectionApi, plugins, effect, options = {}) {
  const pluginNames = useStaticPlugins(plugins);

  // Create a memoized object containing the named plugins
  const namedExternalPlugins = useMemo(() => pluginNames.reduce((acc, pluginName) => ({
    ...acc,
    [`${String(pluginName)}State`]: injectionApi === null || injectionApi === void 0 ? void 0 : injectionApi[pluginName]
  }), {}), [injectionApi, pluginNames]);
  usePluginStateEffectInternal(namedExternalPlugins, effect, options);
}
function usePluginStateEffectInternal(externalPlugins, effect, options = {}) {
  const refStates = useRef();
  const cleanup = useRef();
  const latestEffect = useRef(effect);

  // We should store the latest effect in a reference so it is more intuitive to the user
  // and we are not causing a memory leak by having references to old state.
  useLayoutEffect(() => {
    if (options.disabled) {
      return;
    }
    latestEffect.current = debounce(effect);
    return () => {
      latestEffect.current = undefined;
    };
  }, [effect, options.disabled]);
  useLayoutEffect(() => {
    var _latestEffect$current;
    if (options.disabled) {
      return;
    }

    // Update the reference for this plugin and activate the effect
    refStates.current = mapValues(externalPlugins, value => value === null || value === void 0 ? void 0 : value.sharedState.currentState());
    cleanup.current = (_latestEffect$current = latestEffect.current) === null || _latestEffect$current === void 0 ? void 0 : _latestEffect$current.call(latestEffect, refStates.current);
    const unsubs = Object.entries(externalPlugins).map(([pluginKey, externalPlugin]) => externalPlugin === null || externalPlugin === void 0 ? void 0 : externalPlugin.sharedState.onChange(({
      nextSharedState,
      prevSharedState
    }) => {
      if (prevSharedState !== nextSharedState && refStates.current) {
        var _latestEffect$current2;
        // Update the reference for this plugin and activate the effect
        refStates.current[pluginKey] = nextSharedState;
        cleanup.current = (_latestEffect$current2 = latestEffect.current) === null || _latestEffect$current2 === void 0 ? void 0 : _latestEffect$current2.call(latestEffect, refStates.current);
      }
    }));
    return () => {
      var _cleanup$current;
      refStates.current = undefined;
      unsubs.forEach(cb => cb === null || cb === void 0 ? void 0 : cb());
      (_cleanup$current = cleanup.current) === null || _cleanup$current === void 0 ? void 0 : _cleanup$current.call(cleanup);
    };
    // Do not re-run if the `effect` changes - this is not expected with `useEffect` or similar hooks
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [externalPlugins, options.disabled]);
}