import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { listShopDealerWithdraw } from '@/api/shop/shopDealerWithdraw'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '佣金明细',
})

const CommissionPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [records, setRecords] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const scrollHeight = useScrollHeight(44)


  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    fetchRecords()
  }, [isLoggedIn])

  const fetchRecords = async () => {
    try {
      const data = await listShopDealerWithdraw({})
      setRecords(data || [])
    } catch (e) {
      console.error('获取佣金记录失败:', e)
    } finally {
      setLoading(false)
    }
  }

  const getStatusText = (status: number) => {
    const statusMap: Record<number, string> = {
      0: '待审核',
      10: '审核通过',
      20: '待收款',
      30: '已拒绝',
      40: '已完成',
    }
    return statusMap[status] || '未知'
  }

  if (!isLoggedIn) {
    return null
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {loading ? (
          <View className='flex items-center justify-center py-10'>
            <Text className='text-gray-400'>加载中...</Text>
          </View>
        ) : records.length === 0 ? (
          <EmptyState text='暂无佣金记录' />
        ) : (
          <View className='p-3'>
            {records.map((item) => (
              <View key={item.id} className='bg-white rounded-lg p-3 mb-2'>
                <View className='flex justify-between items-center mb-1'>
                  <Text className='text-sm font-medium text-gray-800'>
                    {item.type === 'withdraw' ? '佣金提现' : '佣金收入'}
                  </Text>
                  <Text
                    className={`text-sm font-bold ${
                      item.amount > 0 ? 'text-green-500' : 'text-red-500'
                    }`}
                  >
                    {item.amount > 0 ? `+${item.amount}` : item.amount}
                  </Text>
                </View>
                <View className='flex justify-between items-center'>
                  <Text className='text-xs text-gray-400'>{item.createTime}</Text>
                  <Text className='text-xs text-gray-500'>{getStatusText(item.status)}</Text>
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default CommissionPage
