import { useState, useEffect, useCallback } from 'react'
import {useUser} from "@/hooks/useUser";
import Taro from '@tarojs/taro'
import { getUserCardStats } from '@/api/user'

interface UserData {
  balance: string
  points: number
  coupons: number
  giftCards: number
  orders: {
    pending: number
    paid: number
    shipped: number
    completed: number
    refund: number
  }
}

interface UseUserDataReturn {
  data: UserData | null
  loading: boolean
  error: string | null
  refresh: () => Promise<void>
  updateBalance: (newBalance: string) => void
  updatePoints: (newPoints: number) => void
}

export const useUserData = (): UseUserDataReturn => {
  const [data, setData] = useState<UserData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // 获取用户数据
  const fetchUserData = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)

      if(!Taro.getStorageSync('UserId')){
        return;
      }

      // 聚合接口：一次请求返回余额/积分/优惠券/礼品卡统计（后端可按用户做缓存）
      const stats = await getUserCardStats()

      const newData: UserData = {
        balance: stats?.balance || '0.00',
        points: stats?.points || 0,
        coupons: stats?.coupons || 0,
        giftCards: stats?.giftCards || 0,
        orders: {
          pending: 0,
          paid: 0,
          shipped: 0,
          completed: 0,
          refund: 0
        }
      }

      setData(newData)
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取用户数据失败')
    } finally {
      setLoading(false)
    }
  }, [])

  // 刷新数据
  const refresh = useCallback(async () => {
    await fetchUserData()
  }, [fetchUserData])

  // 更新余额（本地更新，避免频繁请求）
  const updateBalance = useCallback((newBalance: string) => {
    setData(prev => prev ? { ...prev, balance: newBalance } : null)
  }, [])

  // 更新积分
  const updatePoints = useCallback((newPoints: number) => {
    setData(prev => prev ? { ...prev, points: newPoints } : null)
  }, [])

  // 初始化加载
  useEffect(() => {
    fetchUserData().then()
  }, [fetchUserData])

  return {
    data,
    loading,
    error,
    refresh,
    updateBalance,
    updatePoints
  }
}

// 轻量级版本 - 只获取基础数据
export const useUserBasicData = () => {
  const {user} = useUser()
  const [balance, setBalance] = useState<number>(0)
  const [points, setPoints] = useState<number>(0)
  const [loading, setLoading] = useState(false)

  const fetchBasicData = useCallback(async () => {
    setLoading(true)
    try {
      setBalance(user?.balance || 0)
      setPoints(user?.points || 0)
    } catch (error) {
      console.error('获取基础数据失败:', error)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchBasicData().then()
  }, [fetchBasicData])

  return {
    balance,
    points,
    loading,
    refresh: fetchBasicData,
    updateBalance: setBalance,
    updatePoints: setPoints
  }
}
