import React, {useState, useEffect, useCallback} 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 {pageShopDealerOrder} from '@/api/shop/shopDealerOrder'
import {useDealerUser} from '@/hooks/useDealerUser'
import type {ShopDealerOrder} from '@/api/shop/shopDealerOrder/model'

interface OrderWithDetails extends ShopDealerOrder {
  orderNo?: string
  customerName?: string
  userCommission?: string
}

const DealerOrders: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false)
  const [refreshing, setRefreshing] = useState<boolean>(false)
  const [loadingMore, setLoadingMore] = useState<boolean>(false)
  const [orders, setOrders] = useState<OrderWithDetails[]>([])
  const [currentPage, setCurrentPage] = useState<number>(1)
  const [hasMore, setHasMore] = useState<boolean>(true)

  const {dealerUser} = useDealerUser()

  // 获取订单数据
  const fetchOrders = 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 pageShopDealerOrder({
        page,
        limit: 10
      })

      if (result?.list) {
        const newOrders = result.list.map(order => ({
          ...order,
          orderNo: `${order.orderId}`,
          customerName: `用户${order.userId}`,
          userCommission: order.firstMoney || '0.00'
        }))

        if (page === 1) {
          setOrders(newOrders)
        } else {
          setOrders(prev => [...prev, ...newOrders])
        }

        setHasMore(newOrders.length === 10)
        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 fetchOrders(1, true)
  }

  // 加载更多
  const handleLoadMore = async () => {
    if (!loadingMore && hasMore) {
      await fetchOrders(currentPage + 1)
    }
  }

  // 初始化加载数据
  useEffect(() => {
    if (dealerUser?.userId) {
      fetchOrders(1)
    }
  }, [fetchOrders])

  const getStatusText = (isSettled?: number, isInvalid?: number) => {
    if (isInvalid === 1) return '已失效'
    if (isSettled === 1) return '已结算'
    return '待结算'
  }

  const getStatusColor = (isSettled?: number, isInvalid?: number) => {
    if (isInvalid === 1) return 'danger'
    if (isSettled === 1) return 'success'
    return 'warning'
  }

  const renderOrderItem = (order: OrderWithDetails) => (
    <View key={order.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">
          订单号：{order.orderNo}
        </Text>
        <Tag type={getStatusColor(order.isSettled, order.isInvalid)}>
          {getStatusText(order.isSettled, order.isInvalid)}
        </Tag>
      </View>

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          订单金额：¥{order.orderPrice || '0.00'}
        </Text>
        <Text className="text-sm text-orange-500 font-semibold">
          我的佣金：¥{order.userCommission}
        </Text>
      </View>

      <View className="flex justify-between items-center">
        <Text className="text-sm text-gray-400">
          客户：{order.customerName}
        </Text>
        <Text className="text-sm text-gray-400">
          {order.createTime}
        </Text>
      </View>
    </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 && orders.length === 0 ? (
              <View className="text-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2">加载中...</Text>
              </View>
            ) : orders.length > 0 ? (
              <>
                {orders.map(renderOrderItem)}
                {loadingMore && (
                  <View className="text-center py-4">
                    <Loading/>
                    <Text className="text-gray-500 mt-1 text-sm">加载更多...</Text>
                  </View>
                )}
                {!hasMore && orders.length > 0 && (
                  <View className="text-center py-4">
                    <Text className="text-gray-400 text-sm">没有更多数据了</Text>
                  </View>
                )}
              </>
            ) : (
              <Empty description="暂无处方" style={{
                backgroundColor: 'transparent'
              }}/>
            )}
          </View>
        </ScrollView>
      </PullToRefresh>
    </View>
  )
}

export default DealerOrders
