import React, { useState } from 'react'
import { View, Text, ScrollView, Input } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { YongrenTabBarLayout } from '@d8d/yongren-shared-ui/components/YongrenTabBarLayout'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { enterpriseOrderClient } from '../../api'
import type { OrderData } from '../../api'

type OrderStatus = 'all' | 'in_progress' | 'completed' | 'cancelled'

/**
 * Hook to fetch order statistics
 * @param orderId Order ID
 * @returns Query result with order stats
 */
const useOrderStats = (orderId: number | undefined) => {
  return useQuery({
    queryKey: ['order-stats', orderId],
    queryFn: async () => {
      if (!orderId) {
        console.debug('[useOrderStats] orderId 为空，跳过 API 调用')
        return null
      }
      console.debug('[useOrderStats] 正在调用统计 API，orderId:', orderId)
      // 路径: /company-orders/:id/stats -> client key: 'company-orders' -> ':id' -> 'stats'
      const response = await enterpriseOrderClient['company-orders'][':id']['stats'].$get({
        param: { id: orderId },
        query: {}
      })
      console.debug('[useOrderStats] API 响应状态:', response.status, response.ok)
      if (response.ok) {
        const data = await response.json()
        console.debug('[useOrderStats] API 返回数据:', data)
        return data
      }
      throw new Error('获取订单统计失败')
    },
    enabled: !!orderId,
    staleTime: 5 * 60 * 1000, // 5 minutes cache
    retry: 1
  })
}

/**
 * 订单卡片组件 - 负责显示单个订单和获取统计数据
 */
interface OrderCardProps {
  order: {
    id: number
    orderNumber: string
    name: string
    createdAt: string
    status: string
    statusLabel: string
    statusClass: string
    actualPeople: number
    startDate: string
    endDate: string
    talentName: string
    position: string
  }
  onViewDetail: (orderId: number) => void
}

const OrderCard: React.FC<OrderCardProps> = ({ order, onViewDetail }) => {
  // 获取订单统计数据
  const { data: statsData, isLoading: statsLoading } = useOrderStats(order.id)

  // 使用 API 返回的数据，或默认值（加载中或失败时）
  const checkinStats = statsData?.checkinStats || { current: 0, total: order.actualPeople, percentage: 0 }
  const salaryVideoStats = statsData?.salaryVideoStats || { current: 0, total: order.actualPeople, percentage: 0 }
  const taxVideoStats = statsData?.taxVideoStats || { current: 0, total: order.actualPeople, percentage: 0 }

  return (
    <View className="card bg-white p-4">
      {/* 订单头部 */}
      <View className="flex justify-between items-start mb-3">
        <View className="flex flex-col">
          <Text className="font-semibold text-gray-800">{order.name}</Text>
          <Text className="text-xs text-gray-500">{order.createdAt} 创建</Text>
        </View>
        <Text className={`text-xs px-2 py-1 rounded-full ${order.statusClass}`}>
          {order.statusLabel}
        </Text>
      </View>

      {/* 订单信息网格 */}
      <View className="grid grid-cols-2 gap-3 text-sm mb-3">
        <View className="flex flex-col">
          <Text className="text-gray-500">实际人数</Text>
          <Text className="text-gray-800">
            {statsLoading ? '...' : `${statsData?.actualPeople ?? order.actualPeople}人`}
          </Text>
        </View>
        <View className="flex flex-col">
          <Text className="text-gray-500">开始日期</Text>
          <Text className="text-gray-800">{order.startDate}</Text>
        </View>
        <View className="flex flex-col col-span-2">
          <Text className="text-gray-500">实际结束</Text>
          <Text className="text-gray-800">{order.endDate}</Text>
        </View>
      </View>

      {/* 打卡数据统计网格 */}
      <View className="grid grid-cols-3 gap-2 mb-3">
        <View className="bg-blue-50 rounded-lg p-2 text-center flex flex-col">
          <Text className="text-xs text-gray-600">本月打卡</Text>
          {statsLoading ? (
            <Text className="text-sm text-gray-400">...</Text>
          ) : (
            <>
              <Text className="text-sm font-bold text-gray-800">
                {checkinStats.current}/{checkinStats.total}
              </Text>
              <Text className="text-xs text-gray-500">{checkinStats.percentage}%</Text>
            </>
          )}
        </View>
        <View className="bg-green-50 rounded-lg p-2 text-center flex flex-col">
          <Text className="text-xs text-gray-600">工资视频</Text>
          {statsLoading ? (
            <Text className="text-sm text-gray-400">...</Text>
          ) : (
            <>
              <Text className="text-sm font-bold text-gray-800">
                {salaryVideoStats.current}/{salaryVideoStats.total}
              </Text>
              <Text className="text-xs text-gray-500">{salaryVideoStats.percentage}%</Text>
            </>
          )}
        </View>
        <View className="bg-purple-50 rounded-lg p-2 text-center flex flex-col">
          <Text className="text-xs text-gray-600">个税视频</Text>
          {statsLoading ? (
            <Text className="text-sm text-gray-400">...</Text>
          ) : (
            <>
              <Text className="text-sm font-bold text-gray-800">
                {taxVideoStats.current}/{taxVideoStats.total}
              </Text>
              <Text className="text-xs text-gray-500">{taxVideoStats.percentage}%</Text>
            </>
          )}
        </View>
      </View>

      {/* 操作按钮区域 */}
      <View className="flex justify-end text-sm">
        <View className="flex items-center text-blue-500" onClick={() => onViewDetail(order.id)}>
          <Text className="i-heroicons-eye-20-solid mr-1" />
          <Text>查看详情</Text>
        </View>
      </View>
    </View>
  )
}

const OrderList: React.FC = () => {
  const [activeStatus, setActiveStatus] = useState<OrderStatus>('all')
  const [searchKeyword, setSearchKeyword] = useState('')
  const [sortBy, _setSortBy] = useState('createTime')
  const [sortOrder, _setSortOrder] = useState<'asc' | 'desc'>('desc')
  const [refreshing, setRefreshing] = useState(false)

  // 使用useInfiniteQuery进行无限滚动分页
  const {
    data,
    isLoading,
    error,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ['company-orders', activeStatus, searchKeyword, sortBy, sortOrder],
    queryFn: async ({ pageParam = 1 }) => {
      const userInfo = getEnterpriseUserInfo()
      const companyId = userInfo?.companyId || 0

      // 构建查询参数
      const queryParams: any = {
        page: pageParam,
        pageSize: 20,
        sortBy,
        sortOrder: sortOrder.toUpperCase()
      }

      // 添加公司ID
      if (companyId) {
        queryParams.companyId = companyId
      }

      // 搜索关键词
      if (searchKeyword) {
        queryParams.orderName = searchKeyword
      }

      // 状态筛选（排除'all'状态）
      if (activeStatus !== 'all') {
        queryParams.orderStatus = activeStatus
      }

      // 调用企业专用订单API
      const response = await enterpriseOrderClient['company-orders'].$get({
        query: queryParams
      })

      if (response.ok) {
        const data = await response.json()
        // 转换API数据到UI格式 - 使用RPC推断的OrderData类型
        const transformedOrders = (data.data || []).map((order: OrderData) => {
          // 统一使用 orderPersons.length 确保与详情页数据一致
          const orderPersonsCount = order.orderPersons?.length ?? 0
          const talentName = order.orderPersons && order.orderPersons.length > 0
            ? order.orderPersons[0].person?.name || '关联人才'
            : '待关联'

          return {
            id: order.id,
            orderNumber: order.orderName ? `ORDER-${order.id}` : `ORDER-${order.id}`,
            name: order.orderName || '未命名订单',
            createdAt: order.createTime ? new Date(order.createTime).toISOString().split('T')[0] : '未知日期',
            status: order.orderStatus || 'draft',
            statusLabel: getStatusLabel(order.orderStatus),
            statusClass: getStatusClass(order.orderStatus),
            actualPeople: orderPersonsCount,
            startDate: order.expectedStartDate ? new Date(order.expectedStartDate).toISOString().split('T')[0] : '未设置',
            endDate: order.actualEndDate ? new Date(order.actualEndDate).toISOString().split('T')[0] : '未结束',
            talentName: talentName,
            position: '未设置' // 岗位字段不存在于API
            // 注意：统计数据现在由 OrderCard 组件通过 useOrderStats hook 单独获取
          }
        })

        return {
          data: transformedOrders,
          meta: { page: pageParam, pageSize: 20, total: data.total || 0, totalPages: Math.ceil((data.total || 0) / 20) }
        }
      } else {
        throw new Error(`获取订单列表失败: ${response.status}`)
      }
    },
    getNextPageParam: (lastPage, allPages) => {
      const totalPages = lastPage.meta?.totalPages || 1
      const currentPage = lastPage.meta?.page || allPages.length
      return currentPage < totalPages ? currentPage + 1 : undefined
    },
    initialPageParam: 1,
    staleTime: 30 * 1000, // 30秒 - 缩短缓存时间以更快获取最新数据
  })

  const statusFilters = [
    { key: 'all', label: '全部订单', activeClass: 'bg-blue-100 text-blue-800', inactiveClass: 'bg-gray-100 text-gray-800' },
    { key: 'in_progress', label: '进行中', activeClass: 'bg-green-100 text-green-800', inactiveClass: 'bg-gray-100 text-gray-800' },
    { key: 'completed', label: '已完成', activeClass: 'bg-blue-100 text-blue-800', inactiveClass: 'bg-gray-100 text-gray-800' },
    { key: 'cancelled', label: '已取消', activeClass: 'bg-gray-100 text-gray-800', inactiveClass: 'bg-gray-100 text-gray-800' },
  ]

  // 状态标签和样式辅助函数
  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'draft': return '草稿'
      case 'confirmed': return '已确认'
      case 'in_progress': return '进行中'
      case 'completed': return '已完成'
      case 'cancelled': return '已取消'
      default: return status
    }
  }

  const getStatusClass = (status: string) => {
    switch (status) {
      case 'draft': return 'bg-gray-100 text-gray-800'
      case 'confirmed': return 'bg-blue-100 text-blue-800'
      case 'in_progress': return 'bg-green-100 text-green-800'
      case 'completed': return 'bg-purple-100 text-purple-800'
      case 'cancelled': return 'bg-red-100 text-red-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  // 获取企业用户信息
  const getEnterpriseUserInfo = () => {
    try {
      const userInfoStr = Taro.getStorageSync('enterpriseUserInfo')
      if (!userInfoStr) return null

      // 尝试解析JSON字符串
      let userInfo = userInfoStr
      if (typeof userInfoStr === 'string') {
        userInfo = JSON.parse(userInfoStr)
      }

      // 处理双重编码情况：{"data": "{\"id\":2,...}"}
      if (userInfo && typeof userInfo === 'object' && userInfo.data) {
        if (typeof userInfo.data === 'string') {
          userInfo = JSON.parse(userInfo.data)
        } else {
          userInfo = userInfo.data
        }
      }

      return userInfo || null
    } catch (error) {
      console.error('获取企业用户信息失败:', error)
      return null
    }
  }

  // 页面显示时自动刷新（从详情页返回时触发）
  useDidShow(() => {
    console.log('订单列表页显示，自动刷新数据')
    // 使用 invalidateQueries 触发重新获取数据
    // refetch() 会使用缓存数据，而 invalidateQueries 会强制重新获取
    refetch()
  })

  // 下拉刷新处理函数
  const handleRefresh = async () => {
    setRefreshing(true)
    try {
      await refetch()
    } finally {
      setRefreshing(false)
    }
  }


  const handleSearch = () => {
    console.log('搜索关键词:', searchKeyword)
    // 使用refetch重新获取数据，queryKey变化会自动触发重新查询
    refetch()
  }

  const handleStatusFilter = (status: OrderStatus) => {
    setActiveStatus(status)
    // queryKey变化会自动触发重新查询
  }

  // 触底加载更多
  const handleScrollToLower = () => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage()
    }
  }

  const handleViewDetail = (orderId: number) => {
    console.log('查看订单详情:', orderId)
    // 跳转到订单详情页
    Taro.navigateTo({
      url: `/pages/yongren/order/detail/index?id=${orderId}`
    })
  }


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

  return (
    <YongrenTabBarLayout activeKey="order">
      <ScrollView
        className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
        scrollY
        onScrollToLower={handleScrollToLower}
        refresherEnabled
        refresherTriggered={refreshing}
        onRefresherRefresh={handleRefresh}
        refresherBackground="#f5f5f5"
      >
        {/* 导航栏 */}
        <Navbar
          title="订单列表"
          leftIcon=""
          leftText=""
          onClickLeft={() => {}}
          backgroundColor="bg-white"
          border={true}
          fixed={true}
          placeholder={true}
        />

        {/* 订单筛选 */}
        <View className="p-4 border-b border-gray-200">
          <View className="flex space-x-2 overflow-x-auto pb-2">
            {statusFilters.map((filter) => (
              <Text
                key={filter.key}
                className={`text-xs px-3 py-1 rounded-full whitespace-nowrap ${
                  activeStatus === filter.key ? filter.activeClass : filter.inactiveClass
                }`}
                onClick={() => handleStatusFilter(filter.key as OrderStatus)}
              >
                {filter.label}
              </Text>
            ))}
          </View>
        </View>

        {/* 搜索栏 */}
        <View className="p-4 border-b border-gray-200">
          <Input
            className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-full"
            placeholder="按订单号、人才姓名搜索"
            value={searchKeyword}
            onInput={(e) => setSearchKeyword(e.detail.value)}
          />
          <View
            className="flex justify-center items-center bg-gray-100 text-gray-800 text-xs px-3 py-2 rounded-lg mt-2 w-full"
            onClick={handleSearch}
          >
            <Text className="i-heroicons-magnifying-glass-20-solid mr-1" />
            <Text>搜索</Text>
          </View>
        </View>

        {/* 订单列表区域 */}
        <View className="p-4">
          {/* 标题 */}
          <View className="mb-4">
            <Text className="font-semibold text-gray-700">订单列表</Text>
          </View>

          {/* 订单卡片列表 */}
          {isLoading && (
            <View className="flex justify-center items-center py-8">
              <Text className="text-gray-500">加载中...</Text>
            </View>
          )}
          {error && (
            <View className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
              <Text className="text-red-700">{error.message || '获取订单列表失败'}</Text>
            </View>
          )}
          {!isLoading && !error && (
            <View className="space-y-4">
              {allOrders.length === 0 ? (
                <View className="flex justify-center items-center py-8">
                  <Text className="text-gray-500">暂无订单数据</Text>
                </View>
              ) : (
                allOrders.map((order) => (
                  <OrderCard
                    key={order.id}
                    order={order}
                    onViewDetail={handleViewDetail}
                  />
                ))
              )}

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

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

export default OrderList