import { createContext, useContext, useLayoutEffect, useMemo, useState, type ReactNode } from 'react'
import { applyTheme, loadTheme, setTheme as persistTheme, type Theme } from './theme'

type ThemeCtx = {
  theme: Theme
  changeTheme: (theme: Theme) => void
}

const ThemeContext = createContext<ThemeCtx>({
  theme: 'light',
  changeTheme: () => undefined,
})

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setThemeState] = useState<Theme>(() => {
    const initial = loadTheme()
    applyTheme(initial)
    return initial
  })

  useLayoutEffect(() => {
    applyTheme(theme)
  }, [theme])

  const value = useMemo(
    () => ({
      theme,
      changeTheme: (next: Theme) => {
        applyTheme(next)
        persistTheme(next)
        setThemeState(next)
      },
    }),
    [theme],
  )

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

export function useTheme() {
  return useContext(ThemeContext)
}
