import { ref, computed } from 'vue'
import { fetchWalletBalance, fetchWalletLedger } from '../api/wallet'
import type { WalletAccount, WalletLedger } from '../api/wallet'

export function useWallet() {
  const balance = ref<WalletAccount | null>(null)
  const ledgers = ref<WalletLedger[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const availableBalance = computed(() => balance.value?.available_balance ?? 0)
  const frozenBalance = computed(() => balance.value?.frozen_balance ?? 0)
  const totalBalance = computed(() => availableBalance.value + frozenBalance.value)

  async function loadBalance() {
    loading.value = true
    error.value = null
    try {
      balance.value = await fetchWalletBalance()
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载余额失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  async function loadLedger(page = 1, pageSize = 20) {
    loading.value = true
    error.value = null
    try {
      const result = await fetchWalletLedger(page, pageSize)
      ledgers.value = result.items
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载账单失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    balance,
    ledgers,
    loading,
    error,
    availableBalance,
    frozenBalance,
    totalBalance,
    loadBalance,
    loadLedger,
  }
}
