import { View, ScrollView, Text } from '@tarojs/components'
import { useInfiniteQuery } from '@tanstack/react-query'
import { useState } from 'react'
import Taro, { usePullDownRefresh, useReachBottom, useRouter } from '@tarojs/taro'
import { orderClient } from '@/api'
import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { useAuth } from '@/utils/auth'
import OrderCard from '@/components/order/OrderCard'
import './index.css'

type OrderResponse = InferResponseType<typeof orderClient.$get, 200>
type Order = OrderResponse['data'][0]

// 订单状态映射 - 根据tcb-shop-demo设计规范
const orderStatusMap = {
  0: { text: '待发货', color: 'text-orange-500', bgColor: 'bg-orange-100' },
  1: { text: '已发货', color: 'text-blue-500', bgColor: 'bg-blue-100' },
  2: { text: '已完成', color: 'text-green-500', bgColor: 'bg-green-100' },
  3: { text: '已退货', color: 'text-red-500', bgColor: 'bg-red-100' }
}

// 支付状态映射 - 根据tcb-shop-demo设计规范
const payStatusMap = {
  0: { text: '未支付', color: 'text-red-500', bgColor: 'bg-red-100' },
  1: { text: '支付中', color: 'text-yellow-500', bgColor: 'bg-yellow-100' },
  2: { text: '已支付', color: 'text-green-500', bgColor: 'bg-green-100' },
  3: { text: '已退款', color: 'text-gray-500', bgColor: 'bg-gray-100' },
  4: { text: '支付失败', color: 'text-red-500', bgColor: 'bg-red-100' },
  5: { text: '已关闭', color: 'text-gray-500', bgColor: 'bg-gray-100' }
}

export default function OrderListPage() {
  const { user } = useAuth()
  const [activeTab, setActiveTab] = useState('all')

  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params

  // 初始化标签状态
  if (params?.tab && activeTab !== params.tab) {
    setActiveTab(params.tab)
  }

  const {
    data,
    isLoading,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ['orders', user?.id, activeTab],
    queryFn: async ({ pageParam = 1 }) => {
      let filters: any = { userId: user?.id }
      
      // 根据标签筛选
      switch (activeTab) {
        case 'unpaid':
          filters.payState = 0
          break
        case 'unshipped':
          filters.payState = 2
          filters.state = 0
          break
        case 'shipped':
          filters.state = 1
          break
        case 'completed':
          filters.state = 2
          break
      }

      const response = await orderClient.$get({
        query: {
          page: pageParam,
          pageSize: 10,
          filters: JSON.stringify(filters),
          sortOrder: 'DESC'
        }
      })
      if (response.status !== 200) {
        throw new Error('获取订单失败')
      }
      return response.json()
    },
    enabled: !!user?.id,
    getNextPageParam: (lastPage) => {
      const { pagination } = lastPage
      const totalPages = Math.ceil(pagination.total / pagination.pageSize)
      return pagination.current < totalPages ? pagination.current + 1 : undefined
    },
    staleTime: 5 * 60 * 1000,
    initialPageParam: 1,
  })

  // 合并所有分页数据
  const allOrders = data?.pages.flatMap(page => page.data) || []

  // 使用Taro全局钩子 - 触底加载更多
  useReachBottom(() => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage()
    }
  })

  // 使用Taro全局钩子 - 下拉刷新
  usePullDownRefresh(() => {
    refetch().finally(() => {
      Taro.stopPullDownRefresh()
    })
  })

  // 查看订单详情
  const handleOrderDetail = (order: Order) => {
    Taro.navigateTo({
      url: `/pages/order-detail/index?id=${order.id}`
    })
  }



  // 根据tcb-shop-demo设计规范的标签配置
  const tabs = [
    { key: 'all', label: '全部' },
    { key: 'unpaid', label: '待付款' },
    { key: 'unshipped', label: '待发货' },
    { key: 'shipped', label: '待收货' },
    { key: 'completed', label: '已完成' }
  ]

  return (
    <View className="min-h-screen bg-gray-50">
      <Navbar
        title="我的订单"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />

      {/* 顶部标签栏 - 根据tcb-shop-demo设计规范 */}
      <View className="bg-white shadow-sm">
        <View className="flex flex-row flex-nowrap px-4 overflow-x-auto">
          {tabs.map((tab) => (
            <View
              key={tab.key}
              className={`flex-shrink-0 py-3 px-4 text-center ${
                activeTab === tab.key
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-gray-600'
              }`}
              onClick={() => setActiveTab(tab.key)}
            >
              <Text className="text-sm font-medium whitespace-nowrap">{tab.label}</Text>
            </View>
          ))}
        </View>
      </View>

      <ScrollView
        className="flex-1"
        scrollY
      >
        <View className="p-4">
          {isLoading ? (
            <View className="flex justify-center py-10">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-primary" />
            </View>
          ) : (
            <>
              {allOrders.map((order) => (
                <OrderCard
                  key={order.id}
                  order={order}
                  orderStatusMap={orderStatusMap}
                  payStatusMap={payStatusMap}
                  onViewDetail={handleOrderDetail}
                />
              ))}

              {isFetchingNextPage && (
                <View className="flex justify-center py-4">
                  <View className="i-heroicons-arrow-path-20-solid animate-spin w-6 h-6 text-primary" />
                  <Text className="ml-2 text-sm text-gray-500">加载更多...</Text>
                </View>
              )}

              {!hasNextPage && allOrders.length > 0 && (
                <View className="text-center py-4 text-sm text-gray-400">
                  没有更多了
                </View>
              )}

              {!isLoading && allOrders.length === 0 && (
                <View className="flex flex-col items-center py-20">
                  <View className="i-heroicons-clipboard-document-list-20-solid w-16 h-16 text-gray-300 mb-4" />
                  <Text className="text-gray-500 mb-4">暂无订单</Text>
                  <View
                    className="bg-primary text-white px-6 py-2 rounded-full text-sm font-medium"
                    onClick={() => Taro.navigateTo({ url: '/pages/goods-list/index' })}
                  >
                    去购物
                  </View>
                </View>
              )}
            </>
          )}
        </View>
      </ScrollView>
    </View>
  )
}