import { createContext, useContext, useEffect, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";

import type { components } from "../api/schema";
import { api } from "../api/client";
import i18n, { LOCALE_KEY } from "../i18n";

type ConfigView = components["schemas"]["ConfigView"];

const DEFAULTS: ConfigView = {
  app_name: "Collection Management System",
  default_language: "sv",
  default_timezone: "Europe/Stockholm",
};

const ConfigContext = createContext<ConfigView>(DEFAULTS);

export function useConfig(): ConfigView {
  return useContext(ConfigContext);
}

export function ConfigProvider({ children }: { children: ReactNode }) {
  const { data } = useQuery({
    queryKey: ["config"],
    queryFn: async (): Promise<ConfigView> => {
      const { data, error } = await api.GET("/api/config");

      if (error || !data) throw new Error("failed to load config");

      return data;
    },
    staleTime: Infinity,
  });

  // Default the UI language to the instance default, unless the user has chosen one for
  // this browser (LangSwitch persists to localStorage[LOCALE_KEY]).
  useEffect(() => {
    if (data && !localStorage.getItem(LOCALE_KEY)) {
      void i18n.changeLanguage(data.default_language);
    }
  }, [data]);

  return <ConfigContext.Provider value={data ?? DEFAULTS}>{children}</ConfigContext.Provider>;
}
