import { useEffect, useState, useCallback, useMemo } from "react"
import { AuthService } from "@/services/auth"
import { type Theme, ThemeContext } from "./theme-context"

export function ThemeProvider({
  children,
  initialTheme = "light",
  isAuthenticated = false,
}: {
  children: React.ReactNode
  initialTheme?: Theme
  isAuthenticated?: boolean
}) {
  const [theme, setThemeState] = useState<Theme>(initialTheme)

  useEffect(() => {
    const root = window.document.documentElement
    root.classList.remove("light", "dark")
    root.classList.add(theme)
  }, [theme])

  const setTheme = useCallback(async (newTheme: Theme) => {
    setThemeState(newTheme)
    if (isAuthenticated) {
      try {
        await AuthService.updateTheme(newTheme)
      } catch (error) {
        console.error("Failed to sync theme to backend:", error)
      }
    }
  }, [isAuthenticated])

  const setThemeLocal = useCallback((newTheme: Theme) => {
    setThemeState(newTheme)
  }, [])

  const toggleTheme = useCallback(() => {
    setTheme(theme === "light" ? "dark" : "light")
  }, [theme, setTheme])

  const value = useMemo(() => ({
    theme,
    setTheme,
    setThemeLocal,
    toggleTheme
  }), [theme, setTheme, setThemeLocal, toggleTheme])

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