import { createContext, useContext, useState, useEffect } from "react";
import { Appearance } from "react-native";
import { Uniwind } from "uniwind";

type AppThemeContextType = { themeName: string };

const AppThemeContext = createContext<AppThemeContextType>({ themeName: "light" });

export const AppThemeProvider = ({ children }: { children: React.ReactNode }) => {
  const [themeName, setThemeName] = useState<string>(
    () => Uniwind.currentTheme ?? "light",
  );

  useEffect(() => {
    const sub = Appearance.addChangeListener(({ colorScheme }) => {
      setThemeName(colorScheme ?? "light");
    });
    return () => sub.remove();
  }, []);

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

export const useAppTheme = () => useContext(AppThemeContext);
