import { useMemo } from 'react';

import type allTranslations from '@humanddev/hu-translations';

import { useAuth } from 'src/contexts/JWTContext';
import { type ModulesName, type Translations } from 'src/types/instance';
import { useLokaliseTranslation } from 'src/utils/i18n';

type TranslationsType = typeof allTranslations;

type Namespaces =
  | keyof TranslationsType['es']
  | 'dashboard_sidebar_app'
  | 'sportsPool';

const useCustomServerTranslation = ({
  module: moduleName,
  defaultTranslationKey,
  namespace,
}: {
  module: keyof Translations;
  defaultTranslationKey?: string;
  namespace?: Namespaces;
}): string => {
  const { t } = useLokaliseTranslation(namespace);
  const { instance, user } = useAuth();

  const customTranslation = useMemo(() => {
    if (!user) return null;

    const userLanguage = user.language as keyof ModulesName;
    const moduleNames = instance?.moduleNames;

    return moduleNames?.[userLanguage]?.[moduleName] || null;
  }, [instance, user, moduleName]);

  return customTranslation || t(defaultTranslationKey || moduleName);
};

export default useCustomServerTranslation;
