import React, { createContext, useContext, useState, useEffect } from 'react'
import { themes } from './colors'

const ThemeContext = createContext()

export const useTheme = () => {
  const context = useContext(ThemeContext)
  if (!context) {
    throw new Error('useTheme deve ser usado dentro de um ThemeProvider')
  }
  return context
}

export const ThemeProvider = ({ children, defaultTheme = 'light' }) => {
  const [currentTheme, setCurrentTheme] = useState(defaultTheme)
  
  // Aplicar CSS variables no documento
  useEffect(() => {
    const theme = themes[currentTheme]
    const root = document.documentElement
    
    // Aplicar variáveis CSS
    Object.entries(theme).forEach(([key, value]) => {
      root.style.setProperty(`--theme-${key}`, value)
    })
    
    // Classe para o body
    document.body.className = `theme-${currentTheme}`
  }, [currentTheme])
  
  const switchTheme = (themeName) => {
    if (themes[themeName]) {
      setCurrentTheme(themeName)
    }
  }
  
  const value = {
    theme: themes[currentTheme],
    currentTheme,
    switchTheme,
    availableThemes: Object.keys(themes)
  }
  
  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  )
}