import React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
// 测试是否可以导入共享的测试工具
// 使用本地测试工具
import { setupTestEnv, renderTaroComponent } from './__helpers__/local-test-utils'
import OrderList from '../src/pages/OrderList/OrderList'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

// 测试设置共享测试环境
setupTestEnv()

// 创建测试用的QueryClient
const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
    },
  },
})

// 测试包装器组件
const TestWrapper = ({ children }: { children: React.ReactNode }) => {
  const queryClient = createTestQueryClient()
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}

// 包装的render函数
const renderWithQueryClient = (component: React.ReactElement) => {
  return render(<TestWrapper>{component}</TestWrapper>)
}

// Mock Taro组件
jest.mock('@tarojs/components', () => ({
  View: ({ children, className, ...props }: any) => (
    <div className={className} {...props}>{children}</div>
  ),
  Text: ({ children, className, ...props }: any) => (
    <span className={className} {...props}>{children}</span>
  ),
  ScrollView: ({ children, className, scrollY, ...props }: any) => (
    <div className={className} data-scroll-y={scrollY} {...props}>{children}</div>
  ),
  Input: ({ className, placeholder, value, onInput, ...props }: any) => (
    <input
      className={className}
      placeholder={placeholder}
      value={value}
      onChange={(e) => onInput?.({ detail: { value: e.target.value } })}
      {...props}
    />
  ),
  Button: ({ children, className, onClick, ...props }: any) => (
    <button className={className} onClick={onClick} {...props}>
      {children}
    </button>
  ),
}))

// Mock UI组件
jest.mock('@d8d/yongren-shared-ui/components/YongrenTabBarLayout', () => ({
  YongrenTabBarLayout: ({ children, activeKey }: any) => (
    <div data-testid="yongren-tab-bar-layout" data-active-key={activeKey}>
      {children}
    </div>
  ),
}))

jest.mock('@d8d/mini-shared-ui-components/components/navbar', () => ({
  Navbar: ({ title, leftIcon, leftText, onClickLeft }: any) => (
    <div data-testid="navbar" data-title={title} data-left-icon={leftIcon} data-left-text={leftText}>
      <button onClick={onClickLeft}>Navbar Left</button>
    </div>
  ),
}))

// Mock RPC客户端
jest.mock('@d8d/mini-shared-ui-components/utils/rpc/rpc-client', () => ({
  rpcClient: jest.fn(() => ({
    'company-orders': {
      $get: jest.fn(() => Promise.resolve({
        ok: true,
        json: () => Promise.resolve({
          data: [
            {
              id: 1,
              orderNumber: 'ORDER-2023-11',
              orderName: '阿里巴巴2023-11',
              createTime: '2023-11-01T09:00:00Z',
              orderStatus: 'in_progress',
              expectedPersonCount: 10,
              actualPersonCount: 8,
              expectedStartDate: '2023-11-01',
              expectedEndDate: '2024-01-01',
              talentName: '张三',
              position: '前端开发'
            },
            {
              id: 2,
              orderNumber: 'ORDER-2023-08',
              orderName: '腾讯科技2023-08',
              createTime: '2023-08-15T10:30:00Z',
              orderStatus: 'completed',
              expectedPersonCount: 5,
              actualPersonCount: 5,
              expectedStartDate: '2023-08-15',
              expectedEndDate: '2023-12-15',
              talentName: '李四',
              position: '后端开发'
            },
            {
              id: 3,
              orderNumber: 'ORDER-2023-12',
              orderName: '字节跳动2023-12',
              createTime: '2023-12-01T14:20:00Z',
              orderStatus: 'in_progress',
              expectedPersonCount: 15,
              actualPersonCount: 12,
              expectedStartDate: '2023-12-01',
              expectedEndDate: '2024-03-01',
              talentName: '王五',
              position: '产品经理'
            }
          ],
          meta: { page: 1, pageSize: 20, total: 3, totalPages: 1 }
        })
      }))
    }
  }))
}))

describe('OrderList 组件测试', () => {
  test('渲染订单列表页面', async () => {
    renderWithQueryClient(<OrderList />)

    // 验证Navbar存在（立即渲染）
    expect(screen.getByTestId('navbar')).toBeInTheDocument()
    expect(screen.getByTestId('navbar')).toHaveAttribute('data-title', '订单列表')

    // 验证筛选标签（立即渲染）
    expect(screen.getAllByText('全部订单').length).toBeGreaterThan(0)
    expect(screen.getAllByText('进行中').length).toBeGreaterThan(0)
    expect(screen.getAllByText('已完成').length).toBeGreaterThan(0)
    expect(screen.getAllByText('已取消').length).toBeGreaterThan(0)

    // 验证搜索框（立即渲染）
    expect(screen.getByPlaceholderText('按订单号、人才姓名搜索')).toBeInTheDocument()

    // 等待数据加载并验证订单卡片
    await waitFor(() => {
      expect(screen.getByText('阿里巴巴2023-11')).toBeInTheDocument()
    })

    // 验证其他订单卡片和统计卡片（数据已加载）
    expect(screen.getByText('腾讯科技2023-08')).toBeInTheDocument()
    expect(screen.getByText('字节跳动2023-12')).toBeInTheDocument()
    expect(screen.getAllByText('本月打卡').length).toBeGreaterThan(0)
    expect(screen.getAllByText('工资视频').length).toBeGreaterThan(0)
    expect(screen.getAllByText('个税视频').length).toBeGreaterThan(0)
  })

  test('状态筛选功能', () => {
    renderWithQueryClient(<OrderList />)

    // 初始状态为"全部订单"
    const allOrdersTab = screen.getByText('全部订单')
    expect(allOrdersTab).toHaveClass('bg-blue-100')

    // 点击"进行中"筛选 - 使用更具体的选择器
    const filterTabs = screen.getAllByText('进行中')
    const inProgressTab = filterTabs[0] // 第一个是筛选标签
    fireEvent.click(inProgressTab)

    // 验证样式变化（通过类名检查）
    expect(inProgressTab).toHaveClass('bg-green-100')
  })

  test('搜索功能', () => {
    renderWithQueryClient(<OrderList />)

    const searchInput = screen.getByPlaceholderText('按订单号、人才姓名搜索')
    const searchButton = screen.getByText('搜索')

    // 输入搜索关键词
    fireEvent.change(searchInput, { target: { value: '阿里巴巴' } })
    expect(searchInput).toHaveValue('阿里巴巴')

    // 点击搜索按钮（主要验证没有错误）
    fireEvent.click(searchButton)
  })

  test('查看详情按钮点击', async () => {
    renderWithQueryClient(<OrderList />)

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('阿里巴巴2023-11')).toBeInTheDocument()
    })

    // 获取查看详情按钮
    const viewDetailButtons = screen.getAllByText('查看详情')
    expect(viewDetailButtons.length).toBeGreaterThan(0)

    // 点击第一个查看详情按钮
    fireEvent.click(viewDetailButtons[0])
  })

  // 分页控件已移除，改为无限滚动分页
  // 不再需要分页控件渲染测试
})