import { View, ScrollView, Text } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import Taro from '@tarojs/taro'
import { orderClient } from '@/api'
import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'

type OrderResponse = InferResponseType<typeof orderClient[':id']['$get'], 200>

export default function OrderDetailPage() {
  // 获取订单ID
  const params = Taro.getCurrentInstance().router?.params
  const orderId = params?.id ? parseInt(params.id) : 0

  const { data: order, isLoading } = useQuery({
    queryKey: ['order', orderId],
    queryFn: async () => {
      const response = await orderClient[':id'].$get({
        param: { id: orderId }
      })
      if (response.status !== 200) {
        throw new Error('获取订单详情失败')
      }
      return response.json()
    },
    enabled: orderId > 0,
    staleTime: 5 * 60 * 1000,
  })

  // 解析商品详情
  const parseGoodsDetail = (goodsDetail: string | null) => {
    try {
      return goodsDetail ? JSON.parse(goodsDetail) : []
    } catch {
      return []
    }
  }

  const goods = order ? parseGoodsDetail(order.goodsDetail) : []

  if (isLoading) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
      </View>
    )
  }

  if (!order) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <Text className="text-gray-500">订单不存在</Text>
      </View>
    )
  }

  return (
    <View className="min-h-screen bg-gray-50">
      <Navbar
        title="订单详情"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />
      
      <ScrollView className="flex-1 pt-4 pb-20">
        <View className="px-4 space-y-4">
          {/* 订单状态 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-2">订单状态</Text>
              <View className="flex justify-between items-center">
                <Text className="text-lg font-medium text-blue-500">
                  {order.payState === 0 ? '待付款' : 
                   order.state === 0 ? '待发货' :
                   order.state === 1 ? '待收货' :
                   order.state === 2 ? '已完成' : '已取消'}
                </Text>
                <Text className="text-sm text-gray-500">
                  订单号: {order.orderNo}
                </Text>
              </View>
            </View>
          </Card>

          {/* 收货信息 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-3">收货信息</Text>
              <View>
                <Text className="font-medium">{order.recevierName}</Text>
                <Text className="text-sm text-gray-600">{order.receiverMobile}</Text>
                <Text className="text-sm text-gray-600 mt-1">{order.address}</Text>
              </View>
            </View>
          </Card>

          {/* 商品列表 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-4">商品信息</Text>
              {goods.map((item: any, index: number) => (
                <View key={index} className="flex items-center py-3 border-b border-gray-100 last:border-b-0">
                  <img
                    src={item.image || ''}
                    className="w-16 h-16 rounded-lg mr-3"
                    mode="aspectFill"
                  />
                  <View className="flex-1">
                    <Text className="text-sm font-medium">{item.name}</Text>
                    <Text className="text-sm text-gray-500">
                      ¥{item.price.toFixed(2)} × {item.num}
                    </Text>
                  </View>
                  <Text className="text-red-500 font-bold">
                    ¥{(item.price * item.num).toFixed(2)}
                  </Text>
                </View>
              ))}
            </View>
          </Card>

          {/* 订单金额 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-4">订单金额</Text>
              <View className="space-y-2">
                <View className="flex justify-between">
                  <Text className="text-gray-600">商品总价</Text>
                  <Text>¥{order.amount.toFixed(2)}</Text>
                </View>
                <View className="flex justify-between">
                  <Text className="text-gray-600">运费</Text>
                  <Text>¥{order.freightAmount.toFixed(2)}</Text>
                </View>
                <View className="flex justify-between">
                  <Text className="text-gray-600">优惠</Text>
                  <Text>-¥{order.discountAmount.toFixed(2)}</Text>
                </View>
                <View className="flex justify-between text-lg font-bold border-t pt-2">
                  <Text>实付款</Text>
                  <Text className="text-red-500">¥{order.payAmount.toFixed(2)}</Text>
                </View>
              </View>
            </View>
          </Card>

          {/* 订单信息 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-4">订单信息</Text>
              <View className="space-y-2 text-sm">
                <View className="flex justify-between">
                  <Text className="text-gray-600">订单编号</Text>
                  <Text>{order.orderNo}</Text>
                </View>
                <View className="flex justify-between">
                  <Text className="text-gray-600">创建时间</Text>
                  <Text>{new Date(order.createdAt).toLocaleString()}</Text>
                </View>
                {order.payState === 2 && (
                  <View className="flex justify-between">
                    <Text className="text-gray-600">支付时间</Text>
                    <Text>{new Date(order.createdAt).toLocaleString()}</Text>
                  </View>
                )}
              </View>
            </View>
          </Card>
        </View>
      </ScrollView>

      {/* 底部操作栏 */}
      <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-3">
        <View className="flex space-x-2 justify-end">
          {order.payState === 0 && (
            <>
              <Button variant="outline" onClick={() => {
                Taro.showModal({
                  title: '取消订单',
                  content: '确定要取消订单吗？',
                  success: (res) => {
                    if (res.confirm) {
                      // 调用取消订单API
                      Taro.showToast({
                        title: '已取消订单',
                        icon: 'success'
                      })
                    }
                  }
                })
              }}>
                取消订单
              </Button>
              <Button onClick={() => {
                Taro.navigateTo({
                  url: `/pages/payment/index?orderId=${order.id}`
                })
              }}>
                立即支付
              </Button>
            </>
          )}
          
          {order.state === 1 && (
            <Button onClick={() => {
              Taro.showModal({
                title: '确认收货',
                content: '确认已收到商品吗？',
                success: (res) => {
                  if (res.confirm) {
                    // 调用确认收货API
                    Taro.showToast({
                      title: '已确认收货',
                      icon: 'success'
                    })
                  }
                }
              })
            }}>
              确认收货
            </Button>
          )}
          
          {order.state === 2 && (
            <Button variant="outline" onClick={() => {
              Taro.navigateTo({
                url: `/pages/order-refund/index?orderId=${order.id}`
              })
            }}>
              申请退款
            </Button>
          )}
        </View>
      </View>
    </View>
  )
}