import {
  createContext,
  useContext,
  type PropsWithChildren,
} from 'react'
import {useColorScheme} from 'react-native'

import {themes} from './themes'
import type {Theme, ThemeName} from './types'

type SprinklesContextValue = {
  theme: Theme
  themeName: ThemeName
}

const SprinklesContext = createContext<SprinklesContextValue>({
  theme: themes.light,
  themeName: 'light',
})

export function SprinklesProvider({children}: PropsWithChildren) {
  const scheme = useColorScheme()
  const themeName: ThemeName = scheme === 'dark' ? 'dark' : 'light'

  return (
    <SprinklesContext.Provider
      value={{theme: themes[themeName], themeName}}
    >
      {children}
    </SprinklesContext.Provider>
  )
}

export function useSprinkles(): SprinklesContextValue {
  return useContext(SprinklesContext)
}

export function useTheme(): Theme {
  return useContext(SprinklesContext).theme
}
