import React, {useCallback, useEffect, useState} from 'react'
import {View, Text, ScrollView} from '@tarojs/components'
import {Empty, Tag, PullToRefresh, Loading} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {pageShopDealerCapital} from '@/api/shop/shopDealerCapital'
import {useDealerUser} from '@/hooks/useDealerUser'
import type {ShopDealerCapital} from '@/api/shop/shopDealerCapital/model'

const PAGE_SIZE = 10

const DealerCapital: React.FC = () => {
  const {dealerUser} = useDealerUser()

  const [loading, setLoading] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [loadingMore, setLoadingMore] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [records, setRecords] = useState<ShopDealerCapital[]>([])

  const getFlowTypeText = (flowType?: number) => {
    switch (flowType) {
      case 10:
        return '佣金收入'
      case 20:
        return '提现支出'
      case 30:
        return '转账支出'
      case 40:
        return '转账收入'
      default:
        return '资金变动'
    }
  }

  const getFlowTypeTag = (flowType?: number) => {
    // 收入：success；支出：danger；其它：default
    if (flowType === 10 || flowType === 40) return 'success'
    if (flowType === 20 || flowType === 30) return 'danger'
    return 'default'
  }

  const formatMoney = (flowType?: number, money?: string) => {
    const isIncome = flowType === 10 || flowType === 40
    const isExpense = flowType === 20 || flowType === 30
    const sign = isIncome ? '+' : isExpense ? '-' : ''
    return `${sign}${money || '0.00'}`
  }

  const fetchRecords = useCallback(async (page: number = 1, isRefresh: boolean = false) => {
    if (!dealerUser?.userId) return

    try {
      if (isRefresh) {
        setRefreshing(true)
      } else if (page === 1) {
        setLoading(true)
      } else {
        setLoadingMore(true)
      }

      const result = await pageShopDealerCapital({
        page,
        limit: PAGE_SIZE,
        // 只显示与当前登录用户相关的收益明细
        userId: dealerUser.userId
      })

      const list = result?.list || []
      if (page === 1) {
        setRecords(list)
      } else {
        setRecords(prev => [...prev, ...list])
      }

      setHasMore(list.length === PAGE_SIZE)
      setCurrentPage(page)
    } catch (error) {
      console.error('获取收益明细失败:', error)
      Taro.showToast({
        title: '获取收益明细失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
      setRefreshing(false)
      setLoadingMore(false)
    }
  }, [dealerUser?.userId])

  const handleRefresh = async () => {
    await fetchRecords(1, true)
  }

  const handleLoadMore = async () => {
    if (!loadingMore && hasMore) {
      await fetchRecords(currentPage + 1)
    }
  }

  useEffect(() => {
    if (dealerUser?.userId) {
      fetchRecords(1)
    }
  }, [fetchRecords, dealerUser?.userId])

  if (!dealerUser) {
    return (
      <View className="bg-gray-50 min-h-screen flex items-center justify-center">
        <Loading/>
        <Text className="text-gray-500 mt-2">加载中...</Text>
      </View>
    )
  }

  return (
    <View className="min-h-screen bg-gray-50">
      <PullToRefresh
        onRefresh={handleRefresh}
        disabled={refreshing}
        pullingText="下拉刷新"
        canReleaseText="释放刷新"
        refreshingText="刷新中..."
        completeText="刷新完成"
      >
        <ScrollView
          scrollY
          className="h-screen"
          onScrollToLower={handleLoadMore}
          lowerThreshold={50}
        >
          <View className="p-4">
            {loading && records.length === 0 ? (
              <View className="text-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2">加载中...</Text>
              </View>
            ) : records.length > 0 ? (
              <>
                {records.map((item) => (
                  <View key={item.id} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
                    <View className="flex justify-between items-start mb-1">
                      <Text className="font-semibold text-gray-800">
                        {item.describe || '收益明细'}
                      </Text>
                      <Tag type={getFlowTypeTag(item.flowType)}>
                        {getFlowTypeText(item.flowType)}
                      </Tag>
                    </View>

                    <View className="flex justify-between items-center mb-1">
                      <Text className="text-sm text-gray-400">
                        佣金收入
                      </Text>
                      <Text
                        className={`text-sm font-semibold ${
                          item.flowType === 10 || item.flowType === 40 ? 'text-green-600' :
                            item.flowType === 20 || item.flowType === 30 ? 'text-red-500' :
                              'text-gray-700'
                        }`}
                      >
                        {formatMoney(item.flowType, item.money)}
                      </Text>
                    </View>

                    <View className="flex justify-between items-center">
                      <Text className="text-sm text-gray-400">
                        {/*用户：{item.userId ?? '-'}*/}
                      </Text>
                      <Text className="text-sm text-gray-400">
                        {item.createTime || '-'}
                      </Text>
                    </View>
                  </View>
                ))}

                {loadingMore && (
                  <View className="text-center py-4">
                    <Loading/>
                    <Text className="text-gray-500 mt-1 text-sm">加载更多...</Text>
                  </View>
                )}
                {!hasMore && records.length > 0 && (
                  <View className="text-center py-4">
                    <Text className="text-gray-400 text-sm">没有更多数据了</Text>
                  </View>
                )}
              </>
            ) : (
              <Empty description="暂无收益明细"/>
            )}
          </View>
        </ScrollView>
      </PullToRefresh>
    </View>
  )
}

export default DealerCapital
