import { createContext, type ReactNode, useContext } from 'react';
import {
  TouchableWithoutFeedback,
  useColorScheme,
  SafeAreaView,
  View,
  KeyboardAvoidingView,
  Platform,
  Keyboard,
  StatusBar,
} from 'react-native';
import LightTheme from '../styles/themes/LightTheme';
import DarkTheme from '../styles/themes/DarkTheme';

type ThemeMode = 'light' | 'dark' | 'auto';

interface ThemeProviderProps {
  children: ReactNode;
  mode?: ThemeMode; // 'auto' by default
  customLightTheme?: typeof LightTheme;
  customDarkTheme?: typeof DarkTheme;
}

const ThemeContext = createContext(LightTheme);

export const ThemeProvider = ({
  children,
  mode = 'auto',
  customLightTheme,
  customDarkTheme,
}: ThemeProviderProps) => {
  const colorScheme = useColorScheme();

  // Choose theme based on mode and custom themes
  let theme;
  if (mode === 'light') {
    theme = customLightTheme || LightTheme;
  } else if (mode === 'dark') {
    theme = customDarkTheme || DarkTheme;
  } else {
    theme =
      colorScheme === 'dark'
        ? customDarkTheme || DarkTheme
        : customLightTheme || LightTheme;
  }

  return (
    <ThemeContext.Provider value={theme}>
      <SafeAreaView
        style={{ flex: 1, backgroundColor: theme.Background.screen }}
      >
        <StatusBar
          barStyle={theme.StatusBar.barStyle}
          backgroundColor={theme.Background.screen}
        />
        <TouchableWithoutFeedback
          style={{ flex: 1 }}
          onPress={() => {
            Keyboard.dismiss();
          }}
        >
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
            style={{ flex: 1 }}
          >
            <View style={{ flex: 1 }}>{children}</View>
          </KeyboardAvoidingView>
        </TouchableWithoutFeedback>
      </SafeAreaView>
    </ThemeContext.Provider>
  );
};

export const useTheme = () => useContext(ThemeContext);
