import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { getMyOrders } from '../../api'
import './list.scss'

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

  useDidShow(() => {
    fetchOrders()
  })

  const fetchOrders = async () => {
    try {
      const res = await getMyOrders()
      setOrders(Array.isArray(res) ? res : [])
    } catch (err) {
      console.error(err)
    }
  }

  const goPay = (id) => Taro.navigateTo({ url: `/pages/order/payment?id=${id}` })

  return (
    <View className='page-container'>
      <ScrollView scrollY className='list'>
        {orders.map(order => (
          <View key={order.id} className='card'>
             <View className='header'>
                <Text className='time'>{order.created_at?.substring(0, 10)}</Text>
                <Text className={`status ${order.status}`}>
                    {order.status === 'pending' ? '待支付' : order.status === 'paid' ? '已支付' : order.status}
                </Text>
             </View>
             <View className='body'>
                <Image src={order.config_image || 'https://via.placeholder.com/80'} className='img' mode='aspectFill' />
                <View className='info'>
                    <Text className='name'>{order.config_name}</Text>
                    <Text className='qty'>x {order.quantity}</Text>
                </View>
                <View className='price'>
                    <Text>¥{order.total_price}</Text>
                </View>
             </View>
             <View className='footer'>
                {order.status === 'pending' && <View className='btn-pay' onClick={() => goPay(order.id)}>去支付</View>}
             </View>
          </View>
        ))}
        {orders.length === 0 && <View className='empty'>暂无订单</View>}
      </ScrollView>
    </View>
  )
}
