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

interface Locale {
  name: string;
  code: string;
}
interface TranslationContextType {
  translations: Record<string, string>;
  locale: Locale;
  setLanguage: (language: Locale) => void;
  tran: (key: string) => string;
  translateNumber: (input: number | string) => string;
}

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

interface TranslationProviderProps {
  children: ReactNode;
}

export const TranslationProvider: React.FC<TranslationProviderProps> = ({
  children,
}) => {
  const [locale, setLocale] = useState<Locale>({
    name: "English",
    code: "en",
  });

  const [translations, setTranslations] = useState<Record<string, string>>({});

  const getTranslations = useCallback(async (langCode: string) => {
    try {
      const response = await publicInstance.get(`/settings/lang/${langCode}`);
      if (response?.data?.data) {
        setTranslations(response.data.data);
      }
    } catch (error) {
      setTranslations({});
      console.warn(error);
    }
  }, []);

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

  useEffect(() => {
    const loadLanguage = async () => {
      const storedLanguage = storage.getString("language");
      if (storedLanguage) {
        setLanguage(JSON.parse(storedLanguage) as Locale);
      }
    };

    loadLanguage();
  }, [setLanguage]);

  const tran = useCallback(
    (key: string) => {
      if (!translations) return key;
      return translations[key] || key;
    },
    [translations],
  );

  const translateNumber = useCallback(
    (input: number | string): string => {
      return String(input)
        .split("")
        .map((char) =>
          char >= "0" && char <= "9" ? (translations[char] ?? char) : char,
        )
        .join("");
    },
    [translations],
  );

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

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

// Custom hook to use the translation context
export const useTranslations = (): TranslationContextType => {
  const context = useContext(TranslationContext);
  if (!context) {
    throw new Error(
      "useTranslations must be used within a TranslationProvider",
    );
  }
  return context;
};
