import { View, Text } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { distributorEarnings } from '../../api'
import './earnings.scss'

export default function Earnings() {
  const [list, setList] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    fetchData()
  })

  const fetchData = async () => {
    try {
      const res: any = await distributorEarnings()
      // Pagination support check? The backend returns { count, next, previous, results } or just list if no pagination
      if (res.results) {
        setList(res.results)
      } else if (Array.isArray(res)) {
        setList(res)
      }
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className='page-container'>
      {list.length > 0 ? (
          list.map((item: any) => (
              <View className='item' key={item.id}>
                  <View className='row'>
                      <Text className='type'>{item.level === 1 ? '直接推广' : '团队奖励'}</Text>
                      <Text className='amount'>+{item.amount}</Text>
                  </View>
                  <View className='row'>
                      <Text className='source'>
                          {item.order_info?.customer_name} - 订单金额 ¥{item.order_info?.total_price}
                      </Text>
                      <Text className='status'>{item.status === 'settled' ? '已结算' : '待结算'}</Text>
                  </View>
                  <Text className='time'>{item.created_at?.replace('T', ' ').substring(0, 19)}</Text>
              </View>
          ))
      ) : (
          <View className='empty'>暂无收益记录</View>
      )}
    </View>
  )
}
