import React, { createContext, useContext, useState, useEffect, useMemo } from 'react';
import { ThemeProvider, CssBaseline } from '@mui/material';
import { getTheme } from './SteamTheme';
import type { ThemeType } from './SteamTheme';

interface ThemeContextType {
  currentTheme: ThemeType;
  setTheme: (theme: ThemeType) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const AppThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [currentTheme, setCurrentTheme] = useState<ThemeType>('steam');

  useEffect(() => {
    // Load theme from store on startup
    const loadTheme = async () => {
      const api = (window as any).electronAPI;
      if (api?.getServerConfig) {
        const config = await api.getServerConfig();
        if (config?.theme) setCurrentTheme(config.theme);
      }
    };
    loadTheme();
  }, []);

  const setTheme = async (theme: ThemeType) => {
    setCurrentTheme(theme);
    const api = (window as any).electronAPI;
    if (api?.updateServerConfig) {
      await api.updateServerConfig({ theme });
    }
  };

  const theme = useMemo(() => getTheme(currentTheme), [currentTheme]);

  return (
    <ThemeContext.Provider value={{ currentTheme, setTheme }}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        {children}
      </ThemeProvider>
    </ThemeContext.Provider>
  );
};

export const useAppTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) throw new Error('useAppTheme must be used within AppThemeProvider');
  return context;
};
