
import React, { createContext, useState, useEffect, useContext, ReactNode } from 'react';
import { Theme } from '../types';

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

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

export const ThemeProvider = ({ children }: { children: ReactNode }) => {
  const [theme, setTheme] = useState<Theme>(() => {
    try {
      const storedTheme = localStorage.getItem('theme');
      return (storedTheme as Theme) || Theme.System;
    } catch (error) {
      console.warn('Could not access localStorage. Defaulting to system theme.', error);
      return Theme.System;
    }
  });

  useEffect(() => {
    const root = window.document.documentElement;
    const systemIsDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    if (theme === Theme.System) {
      root.classList.toggle('dark', systemIsDark);
    } else {
      root.classList.toggle('dark', theme === Theme.Dark);
    }

    try {
      localStorage.setItem('theme', theme);
    } catch (error) {
      console.warn(`Could not save theme to localStorage: ${error}`);
    }
  }, [theme]);

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

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