"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 { DashboardLabelsProvider } from "@/features/cdc-gpsf/dashboard/dashboard-translation-provider";
import { dashboardOwner } from "@/features/cdc-gpsf/dashboard/dashboard-translations";
import { normalizeDashboardLanguage } from "@/features/cdc-gpsf/dashboard/cdc-gpsf-dashboard-data";
import {
  plenaryDefaults,
  plenaryPage,
  resolvePlenaryLabels,
  fetchPlenaryDictionary,
  type PlenaryLabels,
} from "./plenary-translations";

const Context = createContext<PlenaryLabels | null>(null);
export function PlenaryLabelsProvider({
  text,
  children,
}: {
  text: PlenaryLabels;
  children: ReactNode;
}) {
  return (
    <Context.Provider value={text}>
      <DashboardLabelsProvider text={text}>{children}</DashboardLabelsProvider>
    </Context.Provider>
  );
}
export function PlenaryTranslationProvider({
  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 ? plenaryPage(owner) : null,
      language,
    ],
    queryFn: ({ signal }) =>
      owner
        ? fetchPlenaryDictionary(owner, language, signal)
        : Promise.resolve({}),
    enabled: owner !== null,
    staleTime: 30_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
    retry: 1,
  });
  const text = useMemo(
    () => resolvePlenaryLabels(language, data ?? {}),
    [language, data],
  );
  return <PlenaryLabelsProvider text={text}>{children}</PlenaryLabelsProvider>;
}
export function usePlenaryTranslations() {
  const text = useContext(Context);
  const { language } = useAppLanguage();
  return text ?? plenaryDefaults(language);
}
