"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 { ExportLabelsProvider } from "@/components/ui/export-labels-provider";
import { normalizeDashboardLanguage } from "./cdc-gpsf-dashboard-data";
import {
  dashboardDefaults,
  dashboardOwner,
  dashboardPage,
  fetchDashboardDictionary,
  resolveDashboardLabels,
  type DashboardLabels,
} from "./dashboard-translations";

const Context = createContext<DashboardLabels | null>(null);
export function DashboardLabelsProvider({
  text,
  children,
}: {
  text: DashboardLabels;
  children: ReactNode;
}) {
  return (
    <Context.Provider value={text}>
      <ExportLabelsProvider
        labels={{
          exportChart: text.exportChart,
          CSV: text.csv,
          XLSX: text.xlsx,
          Image: text.image,
        }}
      >
        {children}
      </ExportLabelsProvider>
    </Context.Provider>
  );
}
export function DashboardTranslationProvider({
  children,
}: {
  children: ReactNode;
}) {
  const pathname = usePathname();
  const { language: appLanguage } = useAppLanguage();
  const language = normalizeDashboardLanguage(appLanguage);
  const owner = dashboardOwner(pathname ?? "");
  const { data } = useQuery({
    queryKey: [
      "translations",
      owner,
      owner ? dashboardPage(owner) : null,
      language,
    ],
    queryFn: ({ signal }) =>
      owner
        ? fetchDashboardDictionary(owner, language, signal)
        : Promise.resolve({}),
    enabled: owner !== null,
    staleTime: 30_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
    retry: 1,
  });
  const text = useMemo(
    () => resolveDashboardLabels(language, data ?? {}),
    [language, data],
  );
  return (
    <DashboardLabelsProvider text={text}>{children}</DashboardLabelsProvider>
  );
}
export function useDashboardTranslations() {
  const context = useContext(Context);
  const { language } = useAppLanguage();
  return context ?? dashboardDefaults(language);
}
