"use client"

import { useEffect, useState } from "react"
import type { PropsWithChildren } from "react"
import { ThemeContext } from "@/components/theme-context"
import type { Theme, ThemeContextType } from "@/components/theme-context"
import { DEFAULT_THEME, THEME_CLASS_NAMES, THEME_MEDIA_QUERIES, THEME_VALUES } from "@/shared/constants/theme"
import { STORAGE_KEYS } from "@/shared/constants/storage"

type ThemeProviderProps = PropsWithChildren<{
  readonly defaultTheme?: Theme
  readonly value?: ThemeContextType
}>

const isTheme = (value: string | null | undefined): value is Theme => {
  return value === THEME_VALUES.dark || value === THEME_VALUES.light || value === THEME_VALUES.system
}

export function ThemeProvider({
  children,
  defaultTheme = DEFAULT_THEME,
  value: _value,
  ...props
}: ThemeProviderProps) {
  const [theme, setTheme] = useState<Theme>(() => {
    if (typeof window !== "undefined") {
      const savedTheme = localStorage.getItem(STORAGE_KEYS.theme)
      return isTheme(savedTheme) ? savedTheme : isTheme(defaultTheme) ? defaultTheme : DEFAULT_THEME
    }
    return isTheme(defaultTheme) ? defaultTheme : DEFAULT_THEME
  })

  useEffect(() => {
    const root = window.document.documentElement
    root.classList.remove(THEME_CLASS_NAMES.light, THEME_CLASS_NAMES.dark)

    if (theme === THEME_VALUES.system) {
      const systemTheme = window.matchMedia(THEME_MEDIA_QUERIES.prefersDark)
        .matches
        ? THEME_CLASS_NAMES.dark
        : THEME_CLASS_NAMES.light
      root.classList.add(systemTheme)
      return
    }

    root.classList.add(theme)
  }, [theme])

  const value: ThemeContextType = {
    theme,
    setTheme: (theme: Theme) => {
      localStorage.setItem(STORAGE_KEYS.theme, theme)
      setTheme(theme)
    },
  }

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