import { View, Text, Button, Image } from '@tarojs/components'
import Taro, { useRouter, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { getOrder, prepayMiniprogram } from '../../api'
import { checkLogin } from '../../utils/auth'
import './detail.scss'

export default function OrderDetail() {
  const router = useRouter()
  const { id } = router.params
  const [order, setOrder] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  useLoad(async () => {
    if (id) {
        fetchOrder(Number(id))
    }
  })

  const fetchOrder = async (orderId: number) => {
    try {
        const res = await getOrder(orderId)
        setOrder(res)
    } catch (e) {
        console.error(e)
        Taro.showToast({ title: '获取订单失败', icon: 'none' })
    }
  }

  const handlePay = async () => {
    if (!checkLogin()) return
    if (!order) return
    setLoading(true)
    try {
        const params = await prepayMiniprogram(order.id)
        
        await Taro.requestPayment({
            timeStamp: params.timeStamp,
            nonceStr: params.nonceStr,
            package: params.package,
            signType: params.signType,
            paySign: params.paySign
        })
        
        Taro.showToast({ title: '支付成功', icon: 'success' })
        fetchOrder(order.id) // Refresh order status
        
    } catch (err: any) {
        console.error(err)
        if (err.errMsg && err.errMsg.indexOf('cancel') > -1) {
             Taro.showToast({ title: '取消支付', icon: 'none' })
        } else {
             Taro.showToast({ title: '支付失败', icon: 'none' })
        }
    } finally {
        setLoading(false)
    }
  }

  if (!order) return <View className='page-container'><Text>Loading...</Text></View>

  const isPending = order.status === 'pending'
  const isPaid = order.status === 'paid'

  return (
    <View className='page-container'>
        <View className='status-header'>
            <Text className={`status-text ${order.status}`}>
                {isPending ? '待支付' : isPaid ? '已支付' : order.status}
            </Text>
            <Text className='amount'>¥{order.total_price}</Text>
        </View>

        {/* Product Info */}
        <View className='section-card'>
            <View className='section-title'>商品信息</View>
            <View className='info-row'>
                <Text className='label'>商品名称</Text>
                <Text className='value'>{order.config_name || order.course_title || (order.activity_title ? `报名活动：${order.activity_title}` : '未知商品')}</Text>
            </View>
            <View className='info-row'>
                <Text className='label'>数量</Text>
                <Text className='value'>x {order.quantity}</Text>
            </View>
        </View>

        {/* Shipping Info - Only show if available */}
        {(order.customer_name || order.shipping_address) && (
            <View className='section-card'>
                <View className='section-title'>收货信息</View>
                <View className='info-row'>
                    <Text className='label'>收货人</Text>
                    <Text className='value'>{order.customer_name}</Text>
                </View>
                <View className='info-row'>
                    <Text className='label'>联系电话</Text>
                    <Text className='value'>{order.phone_number}</Text>
                </View>
                {order.shipping_address && (
                    <View className='info-row'>
                        <Text className='label'>收货地址</Text>
                        <Text className='value'>{order.shipping_address}</Text>
                    </View>
                )}
            </View>
        )}

        {/* Logistics Info - Only show if shipped */}
        {(order.courier_name || order.tracking_number) && (
            <View className='section-card'>
                <View className='section-title'>物流信息</View>
                <View className='info-row'>
                    <Text className='label'>快递公司</Text>
                    <Text className='value'>{order.courier_name || '-'}</Text>
                </View>
                <View className='info-row'>
                    <Text className='label'>运单号</Text>
                    <Text className='value'>{order.tracking_number || '-'}</Text>
                </View>
            </View>
        )}

        {/* Order Info */}
        <View className='section-card'>
            <View className='section-title'>订单信息</View>
            <View className='info-row'>
                <Text className='label'>订单编号</Text>
                <Text className='value'>{order.wechat_trade_no || order.id}</Text>
            </View>
            <View className='info-row'>
                <Text className='label'>下单时间</Text>
                <Text className='value'>{order.created_at?.replace('T', ' ').substring(0, 19)}</Text>
            </View>
        </View>

        {isPending && (
            <View className='btn-area safe-area-bottom'>
                <Button className='btn btn-primary' onClick={handlePay} loading={loading}>立即支付</Button>
            </View>
        )}
    </View>
  )
}
