import type {
  NavigationAction,
  NavigationState,
  ParamListBase,
  PartialState,
} from '@react-navigation/routers';
import * as React from 'react';

import type { NavigationContainerEventMap, NavigationHelpers } from './types';

export type ListenerMap = {
  action: ChildActionListener;
  focus: FocusedNavigationListener;
};

export type KeyedListenerMap = {
  getState: GetStateListener;
  beforeRemove: ChildBeforeRemoveListener;
};

export type AddListener = <T extends keyof ListenerMap>(
  type: T,
  listener: ListenerMap[T]
) => void;

export type AddKeyedListener = <T extends keyof KeyedListenerMap>(
  type: T,
  key: string,
  listener: KeyedListenerMap[T]
) => void;

export type ChildActionListener = (
  action: NavigationAction,
  visitedNavigators?: Set<string>
) => boolean;

export type FocusedNavigationCallback<T> = (
  navigation: NavigationHelpers<ParamListBase>
) => T;

export type FocusedNavigationListener = <T>(
  callback: FocusedNavigationCallback<T>
) => {
  handled: boolean;
  result: T;
};

export type GetStateListener = () => NavigationState;

export type WithStackTrace = (
  entry: (...args: never[]) => void,
  callback: () => void
) => void;

export type ChildBeforeRemoveListener = (
  action: NavigationAction,
  nextState: NavigationState | PartialState<NavigationState> | undefined
) => boolean;

type NavigationBuilderContextValue = {
  onAction?: (
    action: NavigationAction,
    visitedNavigators?: Set<string>
  ) => boolean;
  addListener?: AddListener;
  addKeyedListener?: AddKeyedListener;
  onRouteFocus?: (key: string) => void;
  onDispatchAction: (action: NavigationAction, noop: boolean) => void;
  onEmitEvent: (
    event: NavigationContainerEventMap['__unsafe_event__']['data']
  ) => void;
  onOptionsChange: (options: object) => void;
  getIsStateEmitted: () => boolean;
  scheduleUpdate: (callback: () => void) => void;
  flushUpdates: () => void;
  withStackTrace: WithStackTrace;
};

/**
 * Context which holds the required helpers needed to build nested navigators.
 */
export const NavigationBuilderContext = React.createContext<
  NavigationBuilderContextValue | undefined
>(undefined);

export function useNavigationBuilderContext() {
  const value = React.useContext(NavigationBuilderContext);

  if (value == null) {
    throw new Error(
      "Couldn't find a navigation builder context. Is your component inside NavigationContainer?"
    );
  }

  return value;
}
