import React, { createContext, useContext, useEffect, useState } from 'react';
import { useColorScheme, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import useTradeStore from '@/store/useTradeStore';
import { colors } from '@/constants/colors';

// Define theme types
export type ThemeType = 'dark' | 'light';

// Define theme colors
export const lightTheme = {
  background: '#FFFFFF',
  backgroundSecondary: '#F5F5F5',
  card: '#FFFFFF',
  text: '#000000',
  textSecondary: '#555555',
  border: '#DDDDDD',
  primary: colors.primary,
  success: colors.success,
  error: colors.error,
  accent: colors.accent,
  textWhite: '#FFFFFF',
  bgDark: '#F0F0F0',
  bgBlack: '#FAFAFA',
};

export const darkTheme = {
  background: colors.bgBlack,
  backgroundSecondary: colors.bgDark,
  card: colors.bgDark,
  text: colors.textWhite,
  textSecondary: colors.textLightGray,
  border: colors.borderGray,
  primary: colors.primary,
  success: colors.success,
  error: colors.error,
  accent: colors.accent,
  textWhite: colors.textWhite,
  bgDark: colors.bgDark,
  bgBlack: colors.bgBlack,
};

// Create the context
type ThemeContextType = {
  theme: ThemeType;
  colors: typeof darkTheme;
  toggleTheme: () => void;
  setTheme: (theme: ThemeType) => void;
};

const ThemeContext = createContext<ThemeContextType>({
  theme: 'dark',
  colors: darkTheme,
  toggleTheme: () => {},
  setTheme: () => {},
});

// Create the provider component
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { darkMode, setDarkMode } = useTradeStore();
  const systemColorScheme = useColorScheme();
  const [mounted, setMounted] = useState(true); // Set to true by default to ensure rendering
  const [themeState, setThemeState] = useState<ThemeType>(darkMode ? 'dark' : 'light');
  
  // Load theme from AsyncStorage on mount
  useEffect(() => {
    const loadTheme = async () => {
      try {
        const savedTheme = await AsyncStorage.getItem('app-theme');
        if (savedTheme) {
          const parsedTheme = savedTheme as ThemeType;
          setThemeState(parsedTheme);
          // Sync with store
          setDarkMode(parsedTheme === 'dark');
        } else {
          // If no saved theme, use the store's darkMode value
          setThemeState(darkMode ? 'dark' : 'light');
        }
      } catch (error) {
        console.error('Error loading theme from AsyncStorage:', error);
        setThemeState(darkMode ? 'dark' : 'light');
      }
    };
    
    loadTheme();
  }, []);
  
  // Keep theme in sync with store's darkMode
  useEffect(() => {
    if (mounted) {
      setThemeState(darkMode ? 'dark' : 'light');
    }
  }, [darkMode, mounted]);
  
  // Save theme to AsyncStorage whenever it changes
  useEffect(() => {
    if (mounted) {
      const saveTheme = async () => {
        try {
          await AsyncStorage.setItem('app-theme', themeState);
          // Sync with store
          setDarkMode(themeState === 'dark');
        } catch (error) {
          console.error('Error saving theme to AsyncStorage:', error);
        }
      };
      
      saveTheme();
    }
  }, [themeState, mounted, setDarkMode]);
  
  // Toggle theme function
  const handleToggleTheme = () => {
    const newTheme = themeState === 'dark' ? 'light' : 'dark';
    setThemeState(newTheme);
  };
  
  // Set theme directly
  const handleSetTheme = (theme: ThemeType) => {
    setThemeState(theme);
  };
  
  // Get the current theme colors
  const themeColors = themeState === 'dark' ? darkTheme : lightTheme;
  
  // Provide the theme context
  return (
    <ThemeContext.Provider
      value={{
        theme: themeState,
        colors: themeColors,
        toggleTheme: handleToggleTheme,
        setTheme: handleSetTheme,
      }}
    >
      {/* Apply global styles to remove highlight effects */}
      <style type="text/css" nonce="remove-highlight">
        {`
          * {
            -webkit-tap-highlight-color: transparent;
            highlight-color: transparent;
            -webkit-touch-callout: none;
          }
          
          input, textarea, button, select, a, div {
            -webkit-tap-highlight-color: transparent;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
          }
          
          /* Optimize for touch targets */
          button, a, [role="button"], input, select, textarea {
            min-height: 44px;
            min-width: 44px;
          }
          
          /* Improve focus visibility */
          *:focus {
            outline: 2px solid ${colors.primary};
            outline-offset: 2px;
          }
          
          /* Improve text readability */
          body {
            text-rendering: optimizeLegibility;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
          }
        `}
      </style>
      {children}
    </ThemeContext.Provider>
  );
};

// Custom hook to use the theme context
export const useTheme = () => useContext(ThemeContext);