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

/** Value of {@link ToolbarContext} */
export interface ToolbarContextValue<T extends string> {
  /** Current active panel name */
  activePanel: T;
}

const ToolbarContext = createContext<ToolbarContextValue<string> | undefined>(undefined);

/** Provider with data that should be used in {@link Toolbar} */
export function ToolbarContextProvider<T extends string>({
  activePanel,
  children,
}: PropsWithChildren<ToolbarContextValue<T>>) {
  const value: ToolbarContextValue<T> = useMemo(() => ({ activePanel }), [activePanel]);

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

/** Return data that should be used inside {@link Toolbar} */
export function useToolbarContext() {
  const value = useContext(ToolbarContext);
  if (!value) {
    throw new Error('useToolbarContext should be used only inside ToolbarContextProvider');
  }

  return value;
}
