import { createContext, useContext, useEffect, useState } from "react"
import { useTheme as useNextTheme } from "next-themes"

const ThemeProviderContext = createContext({
  theme: "system",
  setTheme: () => null,
  toggleTheme: () => null,
})

// Wrapper to make dashboard components compatible with next-themes
export function ThemeProvider({ children }) {
  const { theme: nextTheme, setTheme: setNextTheme, systemTheme: nextSystemTheme } = useNextTheme()
  
  const toggleTheme = () => {
    if (nextTheme === 'system') {
      const newTheme = nextSystemTheme === 'dark' ? 'light' : 'dark'
      setNextTheme(newTheme)
    } else {
      const newTheme = nextTheme === 'light' ? 'dark' : 'light'
      setNextTheme(newTheme)
    }
  }

  const value = {
    theme: nextTheme || 'system',
    systemTheme: nextSystemTheme || 'light',
    setTheme: setNextTheme,
    toggleTheme,
  }

  return (
    <ThemeProviderContext.Provider value={value}>
      {children}
    </ThemeProviderContext.Provider>
  )
}

export const useTheme = () => {
  const context = useContext(ThemeProviderContext)
  if (context === undefined) {
    throw new Error("useTheme must be used within a ThemeProvider")
  }
  return context
}