import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, yuan, type BackendOrder } from '@/api/backend'
import { Page } from '@/components/ui'
import { ensureStaffLoggedIn } from '@/stores/storage'
import { formatDateTime } from '../shared'

function orderStatusLabel(status: BackendOrder['status']) {
  if (status === 'paid') return '已支付'
  if (status === 'pending_payment') return '待支付'
  if (status === 'closed') return '已关闭'
  return '未知'
}

export default function StaffOrdersPage() {
  const [orders, setOrders] = useState<BackendOrder[]>([])

  async function loadOrders() {
    const token = ensureStaffLoggedIn('/pages/staff/orders/index')
    if (!token) {
      return
    }
    try {
      const result = await backend.staffOrders(token)
      setOrders(result.items)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '订单加载失败', icon: 'none' })
    }
  }

  useDidShow(() => { void loadOrders() })

  return (
    <Page title="所有订单" subtle={`当前 ${orders.length} 个`}>
      <View className="staff-list">
        {orders.map((order) => {
          const titles = order.items.map((item) => item.titleSnapshot).join('、') || '未命名商品'
          return (
            <View key={order.id} className="staff-list-line">
              <View className="staff-list-main">
                <Text className="staff-list-title">{titles}</Text>
                <Text className="staff-list-sub">{order.orderNo} · 用户 {order.userPhone || '-'}</Text>
                <Text className="staff-list-meta">
                  ¥{yuan(order.totalAmount || order.paidAmount || 0).toLocaleString()} · {orderStatusLabel(order.status)} · {formatDateTime(order.createdAt)}
                </Text>
              </View>
              <Text className="staff-list-status">{orderStatusLabel(order.status)}</Text>
            </View>
          )
        })}
        {!orders.length && <View className="staff-empty">暂无订单</View>}
      </View>
    </Page>
  )
}
