import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useRequest } from '@/hooks/useRequest'
import { pageUserRechargeOrder, type RechargeOrder } from '@/api/shop/shopRechargeOrder'

definePageConfig({
  navigationBarTitleText: '充值记录',
})

const tabs = [
  { label: '全部', value: -1 },
  { label: '已支付', value: 20 },
  { label: '待支付', value: 10 },
]

const RechargeRecordPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(-1)
  const [page, setPage] = useState(1)
  const [orders, setOrders] = useState<RechargeOrder[]>([])
  const [hasMore, setHasMore] = useState(true)

  // 获取充值记录
  const { run: fetchOrders, loading } = useRequest(pageUserRechargeOrder, {
    manual: true,
    onSuccess: (data) => {
      if (data?.records) {
        if (page === 1) {
          setOrders(data.records)
        } else {
          setOrders(prev => [...prev, ...data.records])
        }
        setHasMore(data.records.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.payStatus = activeTab
    }
    fetchOrders(params)
  }

  // 初始化加载
  useEffect(() => {
    setPage(1)
    setOrders([])
    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'
    return parseFloat(money).toFixed(2)
  }

  // 格式化时间戳
  const formatTime = (timestamp?: number) => {
    if (!timestamp) return '-'
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  }

  // 获取支付状态文本
  const getStatusText = (status?: number) => {
    return status === 20 ? '已支付' : '待支付'
  }

  // 获取支付状态颜色
  const getStatusColor = (status?: number) => {
    return status === 20 ? 'text-green-600' : 'text-gray-400'
  }

  // 获取支付方式文本
  const getPayMethodText = (method?: string) => {
    if (!method) return '-'
    if (method.includes('wechat') || method.includes('wx')) return '微信支付'
    if (method.includes('alipay') || method.includes('ali')) return '支付宝'
    return method
  }

  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}
      >
        {orders.length === 0 && !loading ? (
          <View className='text-center py-16'>
            <Text className='text-sm text-gray-400'>暂无充值记录</Text>
          </View>
        ) : (
          <View className='p-3'>
            {orders.map(order => (
              <View key={order.orderId} 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'>充值订单</Text>
                    <Text className='text-xs text-gray-400 mt-0 block'>
                      {order.createTime || formatTime(order.payTime)}
                    </Text>
                    {order.orderNo && (
                      <Text className='text-xs text-gray-400 mt-0 block'>
                        订单号: {order.orderNo}
                      </Text>
                    )}
                  </View>
                  <View className='text-right'>
                    <Text className='text-base font-bold text-orange-600'>
                      +¥{formatMoney(order.actualMoney || order.payPrice)}
                    </Text>
                    <Text className={`text-xs mt-0 block ${getStatusColor(order.payStatus)}`}>
                      {getStatusText(order.payStatus)}
                    </Text>
                  </View>
                </View>

                {/* 详细信息 */}
                <View className='mt-2 pt-2 border-t border-gray-100 flex justify-between text-xs text-gray-400'>
                  <Text>支付方式: {getPayMethodText(order.payMethod)}</Text>
                  {order.payStatus === 20 && order.balance && (
                    <Text>余额: ¥{formatMoney(order.balance)}</Text>
                  )}
                </View>

                {/* 赠送金额提示 */}
                {order.payStatus === 20 && order.giftMoney && parseFloat(order.giftMoney) > 0 && (
                  <View className='mt-1 text-xs text-green-600'>
                    含赠送: ¥{formatMoney(order.giftMoney)}
                  </View>
                )}
              </View>
            ))}

            {/* 加载更多 */}
            {hasMore && (
              <View className='text-center py-4'>
                <Text className='text-xs text-gray-400'>
                  {loading ? '加载中...' : '上拉加载更多'}
                </Text>
              </View>
            )}
            {!hasMore && orders.length > 0 && (
              <View className='text-center py-4'>
                <Text className='text-xs text-gray-400'>没有更多了</Text>
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default RechargeRecordPage
