"use client";
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { usePathname } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import {
  normalizeIssueMatrixLanguage,
  type IssueMatrixLanguage,
} from "./components/issue-matrix-i18n";
import {
  fetchIssueMatrixDictionary,
  issueMatrixDefaults,
  issueMatrixModuleFromPath,
  resolveIssueMatrixLabels,
  type IssueMatrixLabels,
  type IssueMatrixModule,
} from "./issue-matrix-translations";

const Context = createContext<{
  language: IssueMatrixLanguage;
  text: IssueMatrixLabels;
} | null>(null);
export function IssueMatrixLabelsProvider({
  children,
  language,
  text,
}: {
  children: ReactNode;
  language: IssueMatrixLanguage;
  text: IssueMatrixLabels;
}) {
  return (
    <Context.Provider value={{ language, text }}>{children}</Context.Provider>
  );
}
export function IssueMatrixTranslationProvider({
  children,
  module,
}: {
  children: ReactNode;
  module?: IssueMatrixModule;
}) {
  const pathname = usePathname();
  const { language: appLanguage } = useAppLanguage();
  const language = normalizeIssueMatrixLanguage(appLanguage);
  const owner = module ?? issueMatrixModuleFromPath(pathname ?? "");
  const page = pathname?.startsWith("/cdc-gpsf/issue-matrix-rgc-decision")
    ? "issue_matrix_rgc_decision" : "issue_matrix";
  const { data } = useQuery({
    queryKey: ["translations", owner, page, language],
    queryFn: ({ signal }) =>
      owner
        ? fetchIssueMatrixDictionary(owner, language, signal, page)
        : Promise.resolve({}),
    enabled: owner !== null,
    staleTime: 30_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
    retry: 1,
  });
  const value = useMemo(
    () => ({ language, text: resolveIssueMatrixLabels(language, data ?? {}) }),
    [language, data],
  );
  return (
    <IssueMatrixLabelsProvider {...value}>{children}</IssueMatrixLabelsProvider>
  );
}
export function useIssueMatrixTranslations(language?: IssueMatrixLanguage) {
  const context = useContext(Context);
  const lang = language ?? context?.language ?? "en";
  return context?.language === lang ? context.text : issueMatrixDefaults(lang);
}
export function useIssueMatrixValueTranslator(language: IssueMatrixLanguage) {
  const text = useIssueMatrixTranslations(language);
  return (
    value: string | number | boolean | null | undefined,
    _language?: IssueMatrixLanguage,
  ) => {
    if (value === null || value === undefined) return "";
    return text.valueLabels[String(value)] ?? String(value);
  };
}
