import React, { useState } from 'react'
import { View, Text, ScrollView, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useInfiniteQuery } 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, OrderListResponse } from '../../api'

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

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

  // 使用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) => {
          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),
            expectedPeople: 0, // 预计人数字段不存在于API，暂设为0
            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
            checkinStats: { current: 0, total: orderPersonsCount, percentage: 0 },
            salaryVideoStats: { current: 0, total: orderPersonsCount, percentage: 0 },
            taxVideoStats: { current: 0, total: orderPersonsCount, percentage: 0 }
          }
        })

        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: 5 * 60 * 1000, // 5分钟
  })

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


  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 handleDownloadVideo = (orderId: number) => {
    console.log('下载订单视频:', orderId)
    // TODO: 下载视频功能
  }

  const handleCreateOrder = () => {
    console.log('创建新订单')
    // TODO: 跳转到创建订单页
  }


  // 合并所有分页数据
  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}
      >
        {/* 导航栏 */}
        <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="flex justify-between items-center mb-4">
            <Text className="font-semibold text-gray-700">订单列表</Text>
            <View
              className="flex items-center bg-blue-500 text-white text-xs px-3 py-1 rounded-lg"
              onClick={handleCreateOrder}
            >
              <Text className="i-heroicons-plus-20-solid mr-1" />
              <Text>新建订单</Text>
            </View>
          </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) => (
                  <View key={order.id} 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">{order.expectedPeople}人</Text>
                      </View>
                      <View className="flex flex-col">
                        <Text className="text-gray-500">实际人数</Text>
                        <Text className="text-gray-800">{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">
                        <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>
                        <Text className="text-sm font-bold text-gray-800">
                          {order.checkinStats.current}/{order.checkinStats.total}
                        </Text>
                        <Text className="text-xs text-gray-500">{order.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>
                        <Text className="text-sm font-bold text-gray-800">
                          {order.salaryVideoStats.current}/{order.salaryVideoStats.total}
                        </Text>
                        <Text className="text-xs text-gray-500">{order.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>
                        <Text className="text-sm font-bold text-gray-800">
                          {order.taxVideoStats.current}/{order.taxVideoStats.total}
                        </Text>
                        <Text className="text-xs text-gray-500">{order.taxVideoStats.percentage}%</Text>
                      </View>
                    </View>

                    {/* 操作按钮区域 */}
                    <View className="flex justify-between text-sm">
                      <View className="flex items-center text-blue-500" onClick={() => handleViewDetail(order.id)}>
                        <Text className="i-heroicons-eye-20-solid mr-1" />
                        <Text>查看详情</Text>
                      </View>
                      <View className="flex items-center text-gray-500" onClick={() => handleDownloadVideo(order.id)}>
                        <Text className="i-heroicons-arrow-down-tray-20-solid mr-1" />
                        <Text>下载视频</Text>
                      </View>
                    </View>
                  </View>
                ))
              )}

              {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