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

/** Value of {@link TestIdAttributeContext} */
export interface TextIdAttributeContextValue {
  /** Attribute that will be used for storing value of `testId` props in components. */
  testIdAttribute: string;
}

/** Context that provide testId attribute that will be used in UI Kit */
const TestIdAttributeContext = createContext<TextIdAttributeContextValue | undefined>(undefined);

/** Provider that inject i18n engine that should be used in UI Kit */
export function TestIdAttributeContextProvider({
  testIdAttribute,
  children,
}: PropsWithChildren<TextIdAttributeContextValue>) {
  const value: TextIdAttributeContextValue = useMemo(() => ({ testIdAttribute }), [testIdAttribute]);

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

/** Return data for testId context that should be used in UI Kit */
export function useTestIdAttributeContext(): TextIdAttributeContextValue {
  const value = useContext(TestIdAttributeContext);
  if (!value) {
    throw new Error('useTestIdAttributeContext should be used only inside TestIdAttributeContextProvider');
  }

  return value;
}
