import { PropsWithChildren, createContext, useContext, useMemo, useRef, useState } from 'react';

/** Value of {@link NavigationBarContext} */
export interface NavigationBarContextValue {
  currentList: string | null;
  previousList: string | null;
  setCurrentList(value: string | null): void;
  panelNode: HTMLElement | null;
}

const NavigationBarContext = createContext<NavigationBarContextValue | null>(null);

export function NavigationBarContextProvider({
  panelNode,
  children,
}: PropsWithChildren<{ panelNode: HTMLElement | null }>) {
  const [currentList, setCurrentList] = useState<string | null>(null);
  const [previousList, setPreviousList] = useState<string | null>(null);
  let timeoutId = useRef<NodeJS.Timeout | null>(null);

  const value = useMemo(() => {
    return {
      currentList,
      previousList,
      setCurrentList(val: string | null) {
        if (timeoutId.current !== null) {
          clearTimeout(timeoutId.current);
        }
        timeoutId.current = setTimeout(() => {
          /* istanbul ignore else */
          if (val !== currentList) {
            setPreviousList(currentList);
            setCurrentList(val);
          }
        }, 100);
      },
      panelNode,
    };
  }, [currentList, setCurrentList, previousList, setPreviousList, panelNode]);

  return <NavigationBarContext.Provider value={value}>{children}</NavigationBarContext.Provider>;
}

export function useNavigationBarContext(): NavigationBarContextValue {
  const value = useContext(NavigationBarContext);
  if (!value) {
    throw new Error('useNavigationBarContext should be used only inside NavigationBarContextProvider');
  }
  return value;
}
