import { View, ScrollView, Text, Image } from '@tarojs/components'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import Taro, { usePullDownRefresh, useRouter } from '@tarojs/taro'
import { orderClient } from '@/api'
import { Navbar } from '@/components/ui/navbar'
import OrderButtonBar from '@/components/order/OrderButtonBar'
import CancelReasonDialog from '@/components/common/CancelReasonDialog'
import { useState } from 'react'
import dayjs from 'dayjs'
import './index.css'

export default function OrderDetailPage() {
  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params
  const orderId = params?.id ? parseInt(params.id) : 0
  const orderNo = params?.order_no || ''
  const queryClient = useQueryClient()

  // 取消原因对话框状态
  const [showCancelDialog, setShowCancelDialog] = useState(false)

  // 通过订单ID或订单号查询订单详情
  const { data: order, isLoading } = useQuery({
    queryKey: ['order', orderId, orderNo],
    queryFn: async () => {
      // 如果提供了订单ID，直接通过ID查询
      if (orderId > 0) {
        const response = await orderClient[':id'].$get({
          param: { id: orderId }
        })
        if (response.status !== 200) {
          throw new Error('获取订单详情失败')
        }
        return response.json()
      }

      // 如果提供了订单号，通过订单列表过滤查询
      if (orderNo) {
        const response = await orderClient.$get({
          query: {
            filters: JSON.stringify({ orderNo }),
            page: 1,
            pageSize: 1
          }
        })
        if (response.status !== 200) {
          throw new Error('获取订单详情失败')
        }
        const data = await response.json()
        if (data.data && data.data.length > 0) {
          return data.data[0]
        } else {
          throw new Error('订单不存在')
        }
      }

      throw new Error('缺少订单参数')
    },
    enabled: orderId > 0 || orderNo !== '',
    staleTime: 5 * 60 * 1000,
  })

  // 使用Taro全局钩子 - 下拉刷新
  usePullDownRefresh(() => {
    queryClient.invalidateQueries({ queryKey: ['order', orderId, orderNo] })
    Taro.stopPullDownRefresh()
  })

  // 取消订单mutation
  const cancelOrderMutation = useMutation({
    mutationFn: async (reason: string) => {
      const response = await orderClient['cancel-order'].$post({
        json: {
          orderId: order?.id || orderId,
          reason
        }
      })
      if (response.status !== 200) {
        throw new Error('取消订单失败')
      }
      return response.json()
    },
    onSuccess: () => {
      // 取消成功后刷新订单数据
      queryClient.invalidateQueries({ queryKey: ['order', orderId, orderNo] })

      // 显示取消成功信息
      Taro.showToast({
        title: '订单取消成功',
        icon: 'success',
        duration: 2000
      })

      // 如果订单已支付，显示退款流程信息
      if (order?.payState === 2) {
        setTimeout(() => {
          Taro.showModal({
            title: '退款处理中',
            content: '您的退款申请已提交，退款金额将在1-3个工作日内原路退回。',
            showCancel: false,
            confirmText: '知道了'
          })
        }, 1500)
      }
    },
    onError: (error) => {
      // 根据错误消息类型显示不同的用户友好提示
      let errorMessage = '取消失败，请稍后重试'

      if (error.message.includes('订单不存在')) {
        errorMessage = '订单不存在或已被删除'
      } else if (error.message.includes('订单状态不允许取消')) {
        errorMessage = '当前订单状态不允许取消'
      } else if (error.message.includes('网络')) {
        errorMessage = '网络连接失败，请检查网络后重试'
      }

      Taro.showToast({
        title: errorMessage,
        icon: 'error',
        duration: 3000
      })
    }
  })

  // 触发取消订单
  const handleCancelOrder = () => {
    // 检查网络连接
    Taro.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          Taro.showToast({
            title: '网络连接失败，请检查网络后重试',
            icon: 'error',
            duration: 3000
          })
          return
        }
        setShowCancelDialog(true)
      },
      fail: () => {
        Taro.showToast({
          title: '网络状态检查失败',
          icon: 'error',
          duration: 3000
        })
      }
    })
  }

  // 处理取消订单确认
  const handleCancelConfirm = (reason: string) => {
    // 显示确认对话框
    Taro.showModal({
      title: '确认取消',
      content: `确定要取消订单吗？\n取消原因：${reason}`,
      success: (confirmRes) => {
        if (confirmRes.confirm) {
          // 调用取消订单API
          cancelOrderMutation.mutate(reason)
          setShowCancelDialog(false)
        }
      }
    })
  }

  // 使用orderGoods关联关系获取商品信息
  const orderGoods = (order as any)?.orderGoods || []

  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>
    )
  }

  // 获取订单状态描述
  const getOrderStatusText = () => {
    if (order.payState === 0) return '待付款'
    if (order.state === 0) return '待发货'
    if (order.state === 1) return '待收货'
    if (order.state === 2) return '已完成'
    return '已取消'
  }

  // 获取订单状态描述详情
  const getOrderStatusDesc = () => {
    if (order.payState === 0) return '请尽快完成支付'
    if (order.state === 0) return '商家正在备货中'
    if (order.state === 1) return '商品已发货，请注意查收'
    if (order.state === 2) return '订单已完成'
    return '订单已取消'
  }

  // 复制订单编号
  const handleCopyOrderNo = () => {
    Taro.setClipboardData({
      data: order.orderNo,
      success: () => {
        Taro.showToast({
          title: '订单号已复制',
          icon: 'success'
        })
      }
    })
  }

  return (
    <View className="order-detail-page">
      <Navbar
        title="订单详情"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />

      <ScrollView
        className="refresh-container"
        scrollY
      >
        {/* 顶部状态卡片 */}
        <View className="order-status-header">
          <Text className="order-status-text">{getOrderStatusText()}</Text>
          <Text className="order-status-desc">{getOrderStatusDesc()}</Text>
        </View>

        {/* 内容区域 */}
        <View className="order-content">
          {/* 收货地址区域 */}
          <View className="order-section">
            <View className="order-section-header">收货信息</View>
            <View className="order-section-body">
              <View className="address-section">
                <View className="address-icon">📍</View>
                <View className="address-info">
                  <Text className="address-receiver">
                    {order.recevierName} {order.receiverMobile}
                  </Text>
                  <Text className="address-detail">{order.address}</Text>
                </View>
                <View className="address-edit" onClick={() => {
                  Taro.showToast({
                    title: '地址修改功能开发中',
                    icon: 'none'
                  })
                }}>
                  修改
                </View>
              </View>
            </View>
          </View>

          {/* 商品列表 */}
          <View className="order-section">
            <View className="order-section-header">商品信息</View>
            <View className="order-section-body">
              {orderGoods.map((item: any, index: number) => (
                <View key={index} className="goods-card">
                  <Image
                    src={item.imageFile?.fullUrl || ''}
                    className="goods-image"
                    mode="aspectFill"
                  />
                  <View className="goods-info">
                    <Text className="goods-name">{item.goodsName}</Text>
                    <Text className="goods-spec">默认规格</Text>
                    <View className="flex justify-between items-center mt-2">
                      <Text className="goods-price">¥{item.price.toFixed(2)}</Text>
                      <Text className="goods-quantity">×{item.num}</Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          </View>

          {/* 支付详情 */}
          <View className="order-section">
            <View className="order-section-header">支付详情</View>
            <View className="order-section-body">
              <View className="pay-detail-item">
                <Text className="pay-detail-label">商品总价</Text>
                <Text className="pay-detail-value">¥{order.amount.toFixed(2)}</Text>
              </View>
              <View className="pay-detail-item">
                <Text className="pay-detail-label">运费</Text>
                <Text className="pay-detail-value">¥{order.freightAmount.toFixed(2)}</Text>
              </View>
              <View className="pay-detail-item">
                <Text className="pay-detail-label">优惠</Text>
                <Text className="pay-detail-value">-¥{order.discountAmount.toFixed(2)}</Text>
              </View>
              <View className="pay-detail-item pay-detail-total">
                <Text className="pay-detail-label">实付款</Text>
                <Text className="pay-detail-value">¥{order.payAmount.toFixed(2)}</Text>
              </View>
            </View>
          </View>

          {/* 订单信息 */}
          <View className="order-section">
            <View className="order-section-header">订单信息</View>
            <View className="order-section-body">
              <View className="order-info-item">
                <Text className="order-info-label">订单编号</Text>
                <View className="flex items-center">
                  <Text className="order-info-value">{order.orderNo}</Text>
                  <View className="order-copy-btn" onClick={handleCopyOrderNo}>
                    复制
                  </View>
                </View>
              </View>
              <View className="order-info-item">
                <Text className="order-info-label">创建时间</Text>
                <Text className="order-info-value">{dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}</Text>
              </View>
              {order.payState === 2 && (
                <View className="order-info-item">
                  <Text className="order-info-label">支付时间</Text>
                  <Text className="order-info-value">{dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}</Text>
                </View>
              )}
            </View>
          </View>
        </View>

        {/* 底部占位区域，防止操作栏遮挡内容 */}
        <View className="order-bottom-padding" />
      </ScrollView>

      {/* 底部操作栏 */}
      <View className="order-action-bar">
        <OrderButtonBar
          order={order}
          onViewDetail={() => {}}
          onCancelOrder={handleCancelOrder}
          hideViewDetail={true}
        />
      </View>

      {/* 取消原因对话框 */}
      <CancelReasonDialog
        open={showCancelDialog}
        onOpenChange={setShowCancelDialog}
        onConfirm={handleCancelConfirm}
        loading={cancelOrderMutation.isPending}
      />
    </View>
  )
}