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

import type { LanguageConfig, LinkComponent } from '../HiveUI';

/** Value for {@link HiveUIContext} */
export interface HiveUIContextValue {
  /** Supported language configs */
  languages: LanguageConfig[];
  /** The first DOM element that was created by Hive UI. It contains styles and can be used as a container for the portals  */
  rootElement: HTMLElement | null;
  linkComponent: LinkComponent;
}

/** Context that returns parameters for HiveUI */
const HiveUIContext = createContext<HiveUIContextValue | undefined>(undefined);

/** Provider that used to pass parameters that used inside HiveUI */
export function HiveUIContextProvider({
  languages,
  linkComponent,
  rootElement,
  children,
}: PropsWithChildren<HiveUIContextValue>) {
  const value: HiveUIContextValue = useMemo(
    () => ({ languages, linkComponent, rootElement }),
    [languages, linkComponent, rootElement],
  );

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

/** Return parameters that should be used inside HiveUI */
export function useHiveUIContext(): HiveUIContextValue {
  const value = useContext(HiveUIContext);
  if (!value) {
    throw new Error('useHiveUIContext should be used only inside HiveUIContextProvider');
  }

  return value;
}
