import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { themeManager, Theme } from '../lib/theme-manager';

interface ThemeContextType {
  theme: Theme;
  effectiveTheme: 'light' | 'dark';
  setTheme: (theme: Theme) => void;
  /**
   * @deprecated Use Tailwind dark: classes instead of checking this value
   */
  isDarkMode: boolean;
}

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

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

interface ThemeProviderProps {
  children: ReactNode;
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  const [theme, setThemeState] = useState<Theme>(themeManager.getTheme());
  const [effectiveTheme, setEffectiveTheme] = useState<'light' | 'dark'>(
    themeManager.getEffectiveTheme()
  );

  useEffect(() => {
    // Subscribe to theme changes
    const unsubscribe = themeManager.subscribe(() => {
      setThemeState(themeManager.getTheme());
      setEffectiveTheme(themeManager.getEffectiveTheme());
    });

    // Initial theme application
    setEffectiveTheme(themeManager.getEffectiveTheme());

    return unsubscribe;
  }, []);

  const setTheme = (newTheme: Theme) => {
    themeManager.setTheme(newTheme);
  };

  return (
    <ThemeContext.Provider
      value={{
        theme,
        effectiveTheme,
        setTheme,
        isDarkMode: effectiveTheme === 'dark', // Deprecated, for backward compatibility
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};
