import { createContext, ReactNode, useContext, useEffect, useState } from 'react'

type Theme = 'light' | 'dark' | 'system'

interface ThemeContextValue {
    theme: Theme
    resolvedTheme: 'light' | 'dark'
    setTheme: (theme: Theme) => void
    toggleTheme: () => void
}

const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)

const THEME_KEY = 'mp-theme'

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

export function ThemeProvider({ children }: { children: ReactNode }) {
    const [theme, setThemeState] = useState<Theme>(() => {
        const stored = localStorage.getItem(THEME_KEY)
        return (stored as Theme) || 'system'
    })
    const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>(() => {
        if (theme === 'system') return getSystemTheme()
        return theme
    })

    useEffect(() => {
        const resolved = theme === 'system' ? getSystemTheme() : theme
        setResolvedTheme(resolved)

        // Apply theme to document
        document.documentElement.classList.remove('light', 'dark')
        document.documentElement.classList.add(resolved)
        document.documentElement.setAttribute('data-theme', resolved)
    }, [theme])

    useEffect(() => {
        // Listen for system theme changes
        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
        const handler = () => {
            if (theme === 'system') {
                const resolved = getSystemTheme()
                setResolvedTheme(resolved)
                document.documentElement.classList.remove('light', 'dark')
                document.documentElement.classList.add(resolved)
            }
        }
        mediaQuery.addEventListener('change', handler)
        return () => mediaQuery.removeEventListener('change', handler)
    }, [theme])

    const setTheme = (newTheme: Theme) => {
        localStorage.setItem(THEME_KEY, newTheme)
        setThemeState(newTheme)
    }

    const toggleTheme = () => {
        const next = resolvedTheme === 'light' ? 'dark' : 'light'
        setTheme(next)
    }

    return (
        <ThemeContext.Provider value={{ theme, resolvedTheme, setTheme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    )
}

export const useTheme = () => {
    const ctx = useContext(ThemeContext)
    if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
    return ctx
}
