"use client";
import {
  createContext,
  ReactNode,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import { publicInstance } from "@/configs/axiosConfig";

interface Locale {
  name: string;
  code: string;
}

interface TranslationContextType {
  translations: Record<string, string>;
  locale: Locale | null;
  setLanguage: (language: Locale) => void;
  tran: (key: string) => string;
}

const TranslationContext = createContext<TranslationContextType | undefined>(
  undefined,
);

export const TranslationProvider = ({ children }: { children: ReactNode }) => {
  const [locale, setLocale] = useState<Locale | null>(null);
  const [translations, setTranslations] = useState<Record<string, string>>({});

  const getTranslations = useCallback(async (langCode: string) => {
    try {
      const res = await publicInstance.get(`/lang/${langCode}`);
      setTranslations(res?.data?.data || {});
    } catch {
      setTranslations({});
    }
  }, []);

  const setLanguage = useCallback(
    (language: Locale) => {
      setLocale(language);
      localStorage.setItem("language", JSON.stringify(language));
      getTranslations(language.code);
    },
    [getTranslations],
  );

  useEffect(() => {
    const stored = localStorage.getItem("language");
    if (stored) {
      try {
        const lang = JSON.parse(stored);
        // eslint-disable-next-line react-hooks/set-state-in-effect
        setLocale(lang);
        getTranslations(lang.code);
      } catch {
        getTranslations("en");
      }
    } else {
      setLocale({ name: "English", code: "en" });
      getTranslations("en");
    }
  }, [getTranslations]);

  const tran = useCallback(
    (key: string) => translations[key] || key,
    [translations],
  );

  const value = useMemo(
    () => ({
      translations,
      locale,
      setLanguage,
      tran,
    }),
    [translations, locale, setLanguage, tran],
  );

  return (
    <TranslationContext.Provider value={value}>
      {children}
    </TranslationContext.Provider>
  );
};

export const useTranslations = () => {
  const ctx = useContext(TranslationContext);
  if (!ctx)
    throw new Error("useTranslations must be used within TranslationProvider");
  return ctx;
};
