import React, {
  createContext,
  useContext,
  ReactNode,
  useCallback,
} from 'react';

export interface DropdownTranslationContextType {
  translations: DropdownTranslate;
}

export const DropdownTranslationContext = createContext<
  DropdownTranslationContextType | undefined
>(undefined);

export const DropdownTranslationProvider: React.FC<{
  children: ReactNode;
  value: DropdownTranslationContextType;
}> = ({ children, value }) => {
  return (
    <DropdownTranslationContext.Provider value={value}>
      {children}
    </DropdownTranslationContext.Provider>
  );
};

type TranslationsKeys =
  | 'emptyState'
  | 'noResultsState'
  | 'placeholder'
  | 'clearButtonTooltip';

type TranslationsMap = {
  [key in TranslationsKeys]: string;
} & {
  selectedItems: (params: { total: number }) => string;
};

export type DropdownTranslate = TranslationsMap;

export const useDropdownTranslationContext = () => {
  const context = useContext(DropdownTranslationContext);

  if (!context) {
    throw new Error(
      'useDropdownTranslationContext must be used within a DropdownTranslationProvider',
    );
  }

  const translate = useCallback(
    (key: keyof DropdownTranslate, options?: { total: number }) => {
      const valueFuncOrString = context.translations[key];

      if (typeof valueFuncOrString === 'function') {
        return valueFuncOrString(options!);
      }

      return valueFuncOrString;
    },
    [context],
  );

  return { translate };
};
