import { createContext, useContext, useEffect, useState, ReactNode } from 'react';

type Theme = 'light' | 'dark';

interface ThemeContextType {
  theme: Theme;
  toggleTheme: () => void;
  setTheme: (theme: Theme) => void;
}

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

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>(() => {
    // 优先从用户设置读取主题
    const savedTheme = localStorage.getItem('smart-agriculture-theme');
    if (savedTheme) {
      return savedTheme as Theme;
    }
    
    // 如果没有用户设置，读取系统默认主题
    const systemSettings = localStorage.getItem('smart_agriculture_system_settings');
    if (systemSettings) {
      try {
        const settings = JSON.parse(systemSettings);
        return settings.defaultTheme || 'light';
      } catch (e) {
        return 'light';
      }
    }
    
    // 默认为 light
    return 'light';
  });

  useEffect(() => {
    // 更新 document 类名
    const root = document.documentElement;
    if (theme === 'dark') {
      root.classList.add('dark');
    } else {
      root.classList.remove('dark');
    }

    // 保存到 localStorage
    localStorage.setItem('smart-agriculture-theme', theme);
  }, [theme]);

  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };

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

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}
