import { ELocalesPlacement } from "@/locales";
import { useMetricABFlags } from "@/services/metric/metricService";
import { selectors } from "@/store";
import { useCallback, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import { useSearchParams } from "react-router-dom";

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

export const useTranslations = (
  placement: ELocalesPlacement = ELocalesPlacement.V0
) => {
  const [searchParams] = useSearchParams();
  const { t, i18n } = useTranslation();
  const gender =
    useSelector(selectors.selectQuestionnaire)?.gender || "default";
  const { flags } = useMetricABFlags();
  const esFlag = flags?.esFlag?.[0];

  const translateVersion = searchParams.get("tv");

  useEffect(() => {
    const _esFlag = localStorage.getItem("esFlag");
    if (!_esFlag?.length && esFlag) {
      localStorage.setItem("esFlag", esFlag);
    }
  }, [esFlag]);

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

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

      const _esFlag = localStorage.getItem("esFlag");

      let _key = key;

      if (placement !== ELocalesPlacement.V0) {
        _key = prefixPlacementKey(prefixGenderKey(key), _placement);
      }

      if (
        _esFlag === "hiCopy" &&
        _placement === ELocalesPlacement.PalmistryV0
      ) {
        _key = prefixPlacementKey(
          prefixGenderKey(key),
          ELocalesPlacement.PalmistryV01
        );
      }

      // Hint translate
      if (translateVersion === "h") {
        _key = prefixPlacementKey(
          prefixGenderKey(key),
          ELocalesPlacement.PalmistryV01
        );
      }

      const translation = t(_key, options);

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

      return translation;
    },
    [placement, prefixGenderKey, prefixPlacementKey, t, translateVersion]
  );

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