import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
} from 'react';
import { useColorScheme } from 'react-native';
import { colors } from './colors';

export type ThemeMode = 'light' | 'dark' | 'system';
export type ThemeColors = typeof colors.light | typeof colors.dark;

interface ThemeContextValue {
  mode: ThemeMode;
  theme: ThemeColors;
  toggleTheme: () => void;
  isDark: boolean;
  setMode: (mode: ThemeMode) => void;
}

const ThemeContext = createContext<ThemeContextValue>({
  mode: 'system',
  theme: colors.light,
  toggleTheme: () => {},
  isDark: false,
  setMode: () => {},
});

export const ThemeProvider = ({ children }: { children: ReactNode }) => {
  const systemColorScheme = useColorScheme(); // 'light' | 'dark' | null
  const [userMode, setUserMode] = useState<ThemeMode>('system');

  // Determine current effective mode
  const getEffectiveMode = (): 'light' | 'dark' => {
    if (userMode === 'system') {
      return systemColorScheme === 'dark' ? 'dark' : 'light';
    }
    return userMode;
  };

  const effectiveMode = getEffectiveMode();
  const isDark = effectiveMode === 'dark';
  const theme = isDark ? colors.dark : colors.light;

  const toggleTheme = () => {
    setUserMode(prev => {
      if (prev === 'system') {
        return systemColorScheme === 'dark' ? 'light' : 'dark';
      }
      return prev === 'light' ? 'dark' : 'light';
    });
  };

  const value: ThemeContextValue = {
    mode: userMode,
    theme,
    toggleTheme,
    isDark,
    setMode: setUserMode,
  };

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

// Simple hook — use this everywhere
export const useTheme = () => useContext(ThemeContext);
