import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useRequest } from '@/hooks/useRequest'
import { pageUserBalanceLog, type UserBalanceLog } from '@/api/system/user/balance-log'

definePageConfig({
  navigationBarTitleText: '余额明细',
})

// 场景类型映射
const SCENE_MAP: Record<number, string> = {
  0: '充值',
  1: '消费',
  2: '退款',
  3: '提现',
  4: '收入',
  5: '支出',
  6: '转账',
  7: '收款',
}

const tabs = [
  { label: '全部', value: -1 },
  { label: '收入', value: 1 },
  { label: '支出', value: 0 },
]

const BalanceLogPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(-1)
  const [page, setPage] = useState(1)
  const [logs, setLogs] = useState<UserBalanceLog[]>([])
  const [hasMore, setHasMore] = useState(true)

  // 获取余额日志
  const { run: fetchLogs, loading } = useRequest(pageUserBalanceLog, {
    manual: true,
    onSuccess: (data) => {
      if (data?.list) {
        if (page === 1) {
          setLogs(data.list)
        } else {
          setLogs(prev => [...prev, ...data.list])
        }
        setHasMore(data.list.length >= 20)
      }
    },
    onError: (err) => {
      Taro.showToast({ title: err.message || '加载失败', icon: 'none' })
    }
  })

  // 加载数据
  const loadData = (pageNum: number = 1) => {
    const params: any = { page: pageNum, limit: 20 }
    if (activeTab === 1) {
      params.moneyGt = 0 // 收入
    } else if (activeTab === 0) {
      params.moneyLt = 0 // 支出
    }
    fetchLogs(params)
  }

  // 初始化加载
  useEffect(() => {
    setPage(1)
    loadData(1)
  }, [activeTab])

  // 加载更多
  const loadMore = () => {
    if (loading || !hasMore) return
    const nextPage = page + 1
    setPage(nextPage)
    loadData(nextPage)
  }

  // 格式化金额
  const formatMoney = (money?: string) => {
    if (!money) return '0.00'
    const num = parseFloat(money)
    return num > 0 ? `+${num.toFixed(2)}` : num.toFixed(2)
  }

  // 获取场景描述
  const getSceneText = (scene?: number) => {
    return SCENE_MAP[scene || 0] || '其他'
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* Tab 栏 */}
      <View className='bg-white flex'>
        {tabs.map(tab => (
          <View
            key={tab.value}
            className={`flex-1 text-center py-3 relative ${
              activeTab === tab.value ? 'text-orange-500 font-medium' : 'text-gray-600'
            }`}
            onClick={() => setActiveTab(tab.value)}
          >
            <Text className='text-sm'>{tab.label}</Text>
            {activeTab === tab.value && (
              <View className='absolute bottom-0 left-0 right-0 flex justify-center'>
                <View className='w-8 h-px bg-orange-500 rounded' />
              </View>
            )}
          </View>
        ))}
      </View>

      {/* 日志列表 */}
      <ScrollView
        scrollY
        className='flex-1'
        onScrollToLower={loadMore}
      >
        {logs.length === 0 && !loading ? (
          <View className='text-center py-16'>
            <Text className='text-sm text-gray-400'>暂无余额明细</Text>
          </View>
        ) : (
          <View className='p-3'>
            {logs.map(log => (
              <View key={log.logId} className='bg-white rounded-lg p-4 mb-2'>
                <View className='flex justify-between items-center'>
                  <View className='flex-1'>
                    <Text className='text-sm text-gray-800 block'>
                      {log.describe || getSceneText(log.scene)}
                    </Text>
                    <Text className='text-xs text-gray-400 mt-0 block'>{log.createTime}</Text>
                  </View>
                  <Text className={`text-base font-bold ${
                    parseFloat(log.money || '0') > 0 ? 'text-green-600' : 'text-red-500'
                  }`}>
                    {formatMoney(log.money)}
                  </Text>
                </View>
                {log.balance !== undefined && (
                  <View className='mt-2 pt-2 border-t border-gray-50'>
                    <Text className='text-xs text-gray-400'>
                      余额: ¥{parseFloat(String(log.balance)).toFixed(2)}
                    </Text>
                  </View>
                )}
              </View>
            ))}
            
            {/* 加载更多 */}
            {hasMore && (
              <View className='text-center py-4'>
                <Text className='text-xs text-gray-400'>
                  {loading ? '加载中...' : '上拉加载更多'}
                </Text>
              </View>
            )}
            {!hasMore && logs.length > 0 && (
              <View className='text-center py-4'>
                <Text className='text-xs text-gray-400'>没有更多了</Text>
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default BalanceLogPage
