import { useState, useEffect, useCallback } from 'react'
import { gradientThemes, type 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 getSavedThemeName = useCallback((): string => {
    try {
      return Taro.getStorageSync('user_theme') || 'nature'
    } catch {
      return 'nature'
    }
  }, [])

  const getStoredUserId = useCallback((): number => {
    try {
      const raw = Taro.getStorageSync('UserId') ?? Taro.getStorageSync('userId')
      const asNumber = typeof raw === 'number' ? raw : parseInt(String(raw || '1'), 10)
      return Number.isFinite(asNumber) ? asNumber : 1
    } catch {
      return 1
    }
  }, [])

  const resolveTheme = useCallback(
    (themeName: string): GradientTheme => {
      if (themeName === 'auto') {
        return gradientUtils.getThemeByUserId(getStoredUserId())
      }
      return gradientThemes.find(t => t.name === themeName) || gradientUtils.getThemeByName('nature') || gradientThemes[0]
    },
    [getStoredUserId]
  )

  const [isAutoTheme, setIsAutoTheme] = useState<boolean>(() => getSavedThemeName() === 'auto')
  const [currentTheme, setCurrentTheme] = useState<GradientTheme>(() => resolveTheme(getSavedThemeName()))

  // 初始化主题
  useEffect(() => {
    const savedTheme = getSavedThemeName()
    setIsAutoTheme(savedTheme === 'auto')
    setCurrentTheme(resolveTheme(savedTheme))
  }, [])

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

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

  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
  }
}
