"use client";

import { I18nextProvider } from "react-i18next";
import { ReactNode, useEffect, useMemo } from "react";
import { Language } from "@/types/global";
import { setCookie } from "cookies-next";
import { DEFAULT_LANGUAGE_CODE } from "@/config/global";
import useSettingsStore from "@/global-store/settings";
import i18n from "@/lib/i18n";
import { TranslationMapContext, setGlobalTranslationMap } from "@/context/translation-map";
import { FA_FALLBACK } from "@/context/fa-fallback";

const ensureI18n = (
  lang: string,
  translation: Record<string, string> | undefined,
  supportedLngs: string[]
) => {
  if (!i18n.isInitialized) {
    i18n.init({
      lng: lang,
      fallbackLng: ["fa", "en"],
      supportedLngs: supportedLngs.length ? supportedLngs : ["fa", "en"],
      defaultNS: "translation",
      fallbackNS: "translation",
      ns: "translation",
      resources: { [lang]: { translation: { ...FA_FALLBACK, ...(translation || {}) } } },
      keySeparator: false,
      nsSeparator: false,
      interpolation: { escapeValue: false },
      returnNull: false,
      returnEmptyString: false,
      initImmediate: true,
      parseMissingKeyHandler: (key: string) => FA_FALLBACK[key] ?? key,
      react: { useSuspense: false },
    });
  } else {
    i18n.addResourceBundle(lang, "translation", { ...FA_FALLBACK, ...(translation || {}) }, true, true);
  }
  if (i18n.language !== lang) {
    i18n.language = lang;
  }
};

const TranslationsProvider = ({
  children,
  locale,
  translation,
  languages,
}: {
  children: ReactNode;
  locale: string;
  translation?: Record<string, string>;
  languages?: Language[];
}) => {
  const { updateSelectedLanguage } = useSettingsStore();

  const supportedLngs = languages?.length
    ? languages?.map((language) => language?.locale)
    : [DEFAULT_LANGUAGE_CODE as string];
  const defaultLanguage = languages?.find((language) => Boolean(language?.default));
  const lang = locale || (DEFAULT_LANGUAGE_CODE as string) || "fa";
  const language = languages?.find((item) => item?.locale === lang);
  const translationMap = useMemo(
    () => ({ ...FA_FALLBACK, ...(translation || {}) }),
    [translation]
  );
  setGlobalTranslationMap(translationMap);
  ensureI18n(lang, translation, supportedLngs);

  useEffect(() => {
    setCookie("defaultLang", defaultLanguage?.locale || DEFAULT_LANGUAGE_CODE || "fa");
    setCookie("locales", supportedLngs);
    setCookie("lang", lang);
    const html = document.documentElement;
    html.setAttribute("lang", lang);
    html.setAttribute(
      "dir",
      language?.backward || lang === "fa" || lang === "ar" ? "rtl" : "ltr"
    );
    if (language) {
      updateSelectedLanguage(language);
    }
    // بدون changeLanguage — از mismatch متن جلوگیری می‌کند
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lang]);

  return (
    <TranslationMapContext.Provider value={translationMap}>
      <I18nextProvider i18n={i18n}>{children}</I18nextProvider>
    </TranslationMapContext.Provider>
  );
};

export default TranslationsProvider;
