import { useState, useEffect } from 'react'
import type { Theme } from '@/types'

export function useTheme() {
  const [theme, setTheme] = useState<Theme>(() => {
    // 从localStorage获取主题设置
    const saved = localStorage.getItem('agriculture-theme')
    if (saved && ['light', 'dark', 'system'].includes(saved)) {
      return saved as Theme
    }
    return 'system'
  })

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

    // 移除之前的主题类
    root.classList.remove('light', 'dark')

    if (theme === 'system') {
      // 使用系统主题
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
        .matches
        ? 'dark'
        : 'light'
      root.classList.add(systemTheme)
    } else {
      // 使用指定主题
      root.classList.add(theme)
    }

    // 保存到localStorage
    localStorage.setItem('agriculture-theme', theme)
  }, [theme])

  // 监听系统主题变化
  useEffect(() => {
    if (theme === 'system') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

      const handleChange = () => {
        const root = window.document.documentElement
        root.classList.remove('light', 'dark')
        root.classList.add(mediaQuery.matches ? 'dark' : 'light')
      }

      mediaQuery.addEventListener('change', handleChange)
      return () => mediaQuery.removeEventListener('change', handleChange)
    }
  }, [theme])

  return {
    theme,
    setTheme,
    isDark: theme === 'dark' || (theme === 'system' &&
      window.matchMedia('(prefers-color-scheme: dark)').matches)
  }
}