import { ELocalesPlacement } from "@/locales";
import { selectors } from "@/store";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";

type TranslationOptions = {
  [key: string]: unknown;
};

export const useTranslations = (
  placement: ELocalesPlacement = ELocalesPlacement.V0
) => {
  const { t, i18n } = useTranslation();
  const gender =
    useSelector(selectors.selectQuestionnaire)?.gender || "default";

  const prefixGenderKey = useCallback(
    (key: string) => `${gender}.${key}`,
    [gender]
  );
  const prefixPlacementKey = useCallback(
    (key: string) => `${placement}.${key}`,
    [placement]
  );

  const translate = useCallback(
    (
      key: string,
      options?: TranslationOptions,
      _placement: ELocalesPlacement = placement
    ) => {
      options = {
        ...options,
        defaultValue: key,
      };

      let _key = key;

      if (_placement === ELocalesPlacement.V1) {
        _key = prefixGenderKey(key);
      }

      if (_placement === ELocalesPlacement.PalmistryV1) {
        _key = prefixGenderKey(prefixPlacementKey(key));
      }

      const translation = t(_key, options);

      if (translation === key) {
        return t(`fallback.${_key}`, options);
      }

      return translation;
    },
    [placement, prefixGenderKey, prefixPlacementKey, t]
  );
  // const translate = (
  //   key: string,
  //   options?: TranslationOptions,
  //   _placement: ELocalesPlacement = placement
  // ) => {
  //   options = {
  //     ...options,
  //     defaultValue: key,
  //   };

  //   let _key = key;

  //   if (_placement === ELocalesPlacement.V1) {
  //     _key = prefixPlacementKey(key);
  //   }

  //   if (_placement === ELocalesPlacement.PalmistryV1) {
  //     _key = prefixGenderKey(prefixPlacementKey(key));
  //   }
  //   return t(_key, options);
  // };

  return useMemo(() => ({ translate, i18n }), [i18n, translate]);
};
