import { createContext, useContext, useEffect, useState } from "react"

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

function getSystemTheme() {
  if (typeof window === 'undefined') return 'light'
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

export function ThemeProvider({
  children,
  storageKey = "vite-ui-theme",
  ...props
}) {
  // Always start with system theme
  const [theme, setTheme] = useState('system')
  const [systemTheme, setSystemTheme] = useState(getSystemTheme)

  // Clear any stored theme on mount
  useEffect(() => {
    localStorage.removeItem(storageKey)
  }, [storageKey])

  useEffect(() => {
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
    
    const handler = (e) => {
      setSystemTheme(e.matches ? 'dark' : 'light')
    }
    
    setSystemTheme(darkModeQuery.matches ? 'dark' : 'light')
    darkModeQuery.addEventListener('change', handler)
    return () => darkModeQuery.removeEventListener('change', handler)
  }, [])

  useEffect(() => {
    const root = window.document.documentElement
    const effectiveTheme = theme === 'system' ? systemTheme : theme
    
    root.classList.remove('light', 'dark')
    root.classList.add(effectiveTheme)
  }, [theme, systemTheme])

  const toggleTheme = () => {
    if (theme === 'system') {
      const newTheme = systemTheme === 'dark' ? 'light' : 'dark'
      setTheme(newTheme)
    } else {
      const newTheme = theme === 'light' ? 'dark' : 'light'
      setTheme(newTheme)
    }
  }

  const value = {
    theme,
    systemTheme,
    setTheme,
    toggleTheme,
  }

  return (
    <ThemeProviderContext.Provider {...props} 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
}