import { useState, useEffect } from 'react'
import { gradientThemes, GradientTheme, gradientUtils } from '@/styles/gradients'
import Taro from '@tarojs/taro'

export interface UseThemeReturn {
  currentTheme: GradientTheme
  setTheme: (themeName: string) => void
  isAutoTheme: boolean
  refreshTheme: () => void
}

/**
 * 主题管理Hook
 * 提供主题切换和状态管理功能
 */
export const useTheme = (): UseThemeReturn => {
  const [currentTheme, setCurrentTheme] = useState<GradientTheme>(gradientThemes[0])
  const [isAutoTheme, setIsAutoTheme] = useState<boolean>(true)

  // 获取当前主题
  const getCurrentTheme = (): GradientTheme => {
    const savedTheme = Taro.getStorageSync('user_theme') || 'auto'
    
    if (savedTheme === 'auto') {
      // 自动主题：根据用户ID生成
      const userId = Taro.getStorageSync('userId') || '1'
      return gradientUtils.getThemeByUserId(userId)
    } else {
      // 手动选择的主题
      return gradientThemes.find(t => t.name === savedTheme) || gradientThemes[0]
    }
  }

  // 初始化主题
  useEffect(() => {
    const savedTheme = Taro.getStorageSync('user_theme') || 'auto'
    setIsAutoTheme(savedTheme === 'auto')
    setCurrentTheme(getCurrentTheme())
  }, [])

  // 设置主题
  const setTheme = (themeName: string) => {
    try {
      Taro.setStorageSync('user_theme', themeName)
      setIsAutoTheme(themeName === 'auto')
      setCurrentTheme(getCurrentTheme())
    } catch (error) {
      console.error('保存主题失败:', error)
    }
  }

  // 刷新主题（用于自动主题模式下用户信息变更时）
  const refreshTheme = () => {
    setCurrentTheme(getCurrentTheme())
  }

  return {
    currentTheme,
    setTheme,
    isAutoTheme,
    refreshTheme
  }
}

/**
 * 获取当前主题的样式对象
 * 用于直接应用到组件样式中
 */
export const useThemeStyles = () => {
  const { currentTheme } = useTheme()
  
  return {
    // 主要背景样式
    primaryBackground: {
      background: currentTheme.background,
      color: currentTheme.textColor
    },
    
    // 按钮样式
    primaryButton: {
      background: currentTheme.background,
      border: 'none',
      color: currentTheme.textColor
    },
    
    // 强调色
    accentColor: currentTheme.primary,
    
    // 文字颜色
    textColor: currentTheme.textColor,
    
    // 完整主题对象
    theme: currentTheme
  }
}
