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

type ThemeMode = 'light' | 'dark';
type AccentTheme = 'blue' | 'purple' | 'green';

interface ThemeContextType {
  mode: ThemeMode;
  accent: AccentTheme;
  setMode: (mode: ThemeMode) => void;
  setAccent: (accent: AccentTheme) => void;
  toggleMode: () => void;
}

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

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setModeState] = useState<ThemeMode>('dark');
  const [accent, setAccentState] = useState<AccentTheme>('blue');

  // Initialize theme from localStorage
  useEffect(() => {
    const savedMode = localStorage.getItem('techzaa-mode') as ThemeMode;
    const savedAccent = localStorage.getItem('techzaa-accent') as AccentTheme;
    
    if (savedMode) setModeState(savedMode);
    if (savedAccent) setAccentState(savedAccent);
  }, []);

  // Apply theme classes to document
  useEffect(() => {
    const root = document.documentElement;
    
    // Apply dark/light mode
    root.classList.remove('light', 'dark');
    root.classList.add(mode);
    
    // Apply accent theme
    root.classList.remove('theme-blue', 'theme-purple', 'theme-green');
    root.classList.add(`theme-${accent}`);
    
    // Save to localStorage
    localStorage.setItem('techzaa-mode', mode);
    localStorage.setItem('techzaa-accent', accent);
  }, [mode, accent]);

  const setMode = (newMode: ThemeMode) => setModeState(newMode);
  const setAccent = (newAccent: AccentTheme) => setAccentState(newAccent);
  const toggleMode = () => setModeState(prev => prev === 'dark' ? 'light' : 'dark');

  return (
    <ThemeContext.Provider value={{ mode, accent, setMode, setAccent, toggleMode }}>
      {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;
}
