import { createContext, useContext, useEffect, useState } from "react";
import { Appearance, useColorScheme as useNativeColorScheme, View } from "react-native";
import { ThemeColors as themeColors } from "@/lib/_core/theme";

export type ColorScheme = "light" | "dark";

interface ThemeContextValue {
  colorScheme: ColorScheme;
  setColorScheme: (scheme: ColorScheme) => void;
}

export const ThemeContext = createContext<ThemeContextValue>({
  colorScheme: "light",
  setColorScheme: () => {},
});

function buildCssVars(scheme: ColorScheme): Record<string, string> {
  const vars: Record<string, string> = {};
  for (const [name, swatch] of Object.entries(themeColors)) {
    vars[`--color-${name}`] = (swatch as any)[scheme];
  }
  return vars;
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  // Use React Native's built-in hook — NOT the app's useColorScheme hook
  // (which would create a circular dependency back into this provider).
  const nativeScheme = useNativeColorScheme();
  const [colorScheme, setColorSchemeState] = useState<ColorScheme>(
    nativeScheme === "dark" ? "dark" : "light",
  );

  const setColorScheme = (scheme: ColorScheme) => {
    setColorSchemeState(scheme);
    Appearance.setColorScheme(scheme);
    if (typeof document !== "undefined") {
      document.documentElement.setAttribute("data-theme", scheme);
      const cssVars = buildCssVars(scheme);
      for (const [key, val] of Object.entries(cssVars)) {
        document.documentElement.style.setProperty(key, val);
      }
    }
  };

  useEffect(() => {
    if (typeof document !== "undefined") {
      document.documentElement.setAttribute("data-theme", colorScheme);
      const cssVars = buildCssVars(colorScheme);
      for (const [key, val] of Object.entries(cssVars)) {
        document.documentElement.style.setProperty(key, val);
      }
    }
  }, [colorScheme]);

  return (
    <ThemeContext.Provider value={{ colorScheme, setColorScheme }}>
      <View
        style={{ flex: 1 }}
        // @ts-ignore – NativeWind dark-mode class
        className={colorScheme === "dark" ? "dark" : ""}
      >
        {children}
      </View>
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  return useContext(ThemeContext);
}

// Alias used by hooks/use-color-scheme.ts and settings screen
export const useThemeContext = useTheme;
