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

type Theme = 'light' | 'dark'

interface ThemeContextType {
    theme: Theme
    setTheme: (theme: Theme) => void
    toggleTheme: () => void
}

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

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

interface ThemeProviderProps {
    children: ReactNode
}

export const ThemeProvider = ({ children }: ThemeProviderProps) => {
    const [theme, setTheme] = useState<Theme>(() => {
        // بررسی تم ذخیره شده در localStorage
        const savedTheme = localStorage.getItem('theme') as Theme
        if (savedTheme) {
            return savedTheme
        }

        // بررسی تنظیمات سیستم
        if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
            return 'dark'
        }

        return 'light'
    })

    useEffect(() => {
        const root = document.documentElement

        // حذف کلاس‌های قبلی
        root.classList.remove('light', 'dark')

        // اضافه کردن کلاس مناسب
        root.classList.add(theme)

        // ذخیره در localStorage
        localStorage.setItem('theme', theme)

        // بروزرسانی رنگ background در body برای CSS قدیمی
        if (theme === 'dark') {
            document.body.style.background = '#1e1e1e'
        } else {
            document.body.style.background = '#eceef6'
        }
    }, [theme])

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

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