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 type PeriodType = "DAY" | "WEEK" | "MONTH" | "YEAR";
type GrammaticalCase = "nominative" | "dat";
type PeriodKeyVariant = "period" | "period_adjective" | "period_without_count";

export const useTranslations = (
  placement: ELocalesPlacement = ELocalesPlacement.V0
) => {
  const [searchParams] = useSearchParams();
  const { t, i18n } = useTranslation();
  const gender =
    useSelector(selectors.selectQuestionnaire)?.gender || "male";
  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, {
        br: <br />,
        ...options
      });

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

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

  const getPeriodText = useCallback(
    (
      periodType: PeriodType,
      count: number,
      grammaticalCase: GrammaticalCase = "nominative",
      periodKeyVariant: PeriodKeyVariant = "period",
    ) => {
      const context = grammaticalCase
      return translate(`${periodKeyVariant}.${periodType.toLowerCase()}`, { count, context });
    },
    [translate, gender]
  );

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