import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import OrderDetail from '../src/pages/OrderDetail/OrderDetail'
import { setupTestEnv } from './__helpers__/local-test-utils'

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>
  ),
  Button: ({ children, className, onClick, ...props }: any) => (
    <button className={className} onClick={onClick} {...props}>
      {children}
    </button>
  ),
  Input: ({ className, placeholder, value, onInput, ...props }: any) => (
    <input
      className={className}
      placeholder={placeholder}
      value={value}
      onChange={(e) => onInput?.({ detail: { value: e.target.value } })}
      {...props}
    />
  ),
  Textarea: ({ className, placeholder, value, onInput, ...props }: any) => (
    <textarea
      className={className}
      placeholder={placeholder}
      value={value}
      onChange={(e) => onInput?.({ detail: { value: e.target.value } })}
      {...props}
    />
  ),
}))

// Mock UI组件
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(() => ({
    detail: {
      ':id': {
        $get: jest.fn(() => Promise.resolve({
          ok: true,
          json: () => Promise.resolve({
            id: 1,
            orderName: '阿里巴巴2023-11',
            orderStatus: 'in_progress',
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString(),
            companyId: 1,
            platformId: 1,
            expectedPersonCount: 30,
            expectedStartDate: new Date().toISOString(),
            actualStartDate: new Date().toISOString(),
            orderPersons: [
              { id: 1, workStatus: 'working', joinDate: new Date().toISOString(), person: { name: '张三', gender: '男', disabilityType: '肢体残疾', phone: '13800138001' } },
              { id: 2, workStatus: 'pre_working', joinDate: new Date().toISOString(), person: { name: '李四', gender: '女', disabilityType: '听力残疾', phone: '13800138002' } },
              { id: 3, workStatus: 'working', joinDate: new Date().toISOString(), person: { name: '王五', gender: '男', disabilityType: '视力残疾', phone: '13800138003' } }
            ]
          })
        }))
      }
    },
    'company-videos': {
      $get: jest.fn(() => Promise.resolve({
        ok: true,
        json: () => Promise.resolve({
          data: [
            { id: 1, assetType: 'checkin_video', file: { name: '打卡视频_2023-12-01.mp4', size: 10485760, uploadTime: new Date().toISOString() } },
            { id: 2, assetType: 'salary_video', file: { name: '工资视频_2023-11-30.mp4', size: 15728640, uploadTime: new Date().toISOString() } }
          ]
        })
      }))
    },
    'checkin-statistics': {
      $get: jest.fn(() => Promise.resolve({
        ok: true,
        json: () => Promise.resolve({
          companyId: 1,
          checkinVideoCount: 15,
          totalVideos: 30
        })
      }))
    },
    'video-statistics': {
      $get: jest.fn(() => Promise.resolve({
        ok: true,
        json: () => Promise.resolve({
          companyId: 1,
          stats: [
            { assetType: 'checkin_video', count: 15, percentage: 50 },
            { assetType: 'salary_video', count: 10, percentage: 33 },
            { assetType: 'tax_video', count: 5, percentage: 17 }
          ],
          total: 30
        })
      }))
    }
  }))
}))

// 模拟Taro方法
import Taro from '@tarojs/taro'

describe('OrderDetail 组件测试', () => {
  beforeEach(() => {
    // 模拟useRouter返回订单ID
    (Taro.useRouter as jest.Mock).mockReturnValue({ params: { id: '1' } })
    // 模拟企业用户信息
    (Taro.getStorageSync as jest.Mock).mockReturnValue(JSON.stringify({
      data: JSON.stringify({
        id: 1,
        companyId: 1,
        name: '测试企业'
      })
    }))
  })

  afterEach(() => {
    jest.clearAllMocks()
  })
  test('渲染订单详情页面', () => {
    renderWithQueryClient(<OrderDetail />)

    // 验证Navbar存在
    expect(screen.getByTestId('navbar')).toBeInTheDocument()
    expect(screen.getByTestId('navbar')).toHaveAttribute('data-title', '订单详情')
    expect(screen.getByTestId('navbar')).toHaveAttribute('data-left-text', '返回')

    // 验证订单信息
    expect(screen.getByText('阿里巴巴2023-11')).toBeInTheDocument()
    expect(screen.getByText('订单编号: ORDER-1')).toBeInTheDocument()
    expect(screen.getAllByText('进行中').length).toBeGreaterThan(0)

    // 验证基本信息卡片
    expect(screen.getByText('基本信息')).toBeInTheDocument()
    expect(screen.getByText('预计人数')).toBeInTheDocument()
    expect(screen.getByText('30人')).toBeInTheDocument()
    expect(screen.getByText('实际人数')).toBeInTheDocument()
    expect(screen.getByText('3人')).toBeInTheDocument()

    // 验证打卡统计卡片
    expect(screen.getByText('打卡数据统计')).toBeInTheDocument()
    expect(screen.getByText('本月打卡')).toBeInTheDocument()
    expect(screen.getByText('工资视频')).toBeInTheDocument()
    expect(screen.getByText('个税视频')).toBeInTheDocument()

    // 验证关联人才卡片
    expect(screen.getByText('关联人才')).toBeInTheDocument()
    expect(screen.getByText('张三')).toBeInTheDocument()
    expect(screen.getByText('李四')).toBeInTheDocument()
    expect(screen.getByText('王五')).toBeInTheDocument()

    // 验证视频资料卡片
    expect(screen.getByText('视频资料')).toBeInTheDocument()
    expect(screen.getByText('打卡视频_2023-12-01.mp4')).toBeInTheDocument()
    expect(screen.getByText('工资视频_2023-11-30.mp4')).toBeInTheDocument()

    // 验证状态管理卡片
    expect(screen.getByText('状态管理')).toBeInTheDocument()
    expect(screen.getByText('草稿')).toBeInTheDocument()
    expect(screen.getByText('已确认')).toBeInTheDocument()
    expect(screen.getAllByText('进行中').length).toBeGreaterThan(0)
    expect(screen.getByText('已完成')).toBeInTheDocument()
    expect(screen.getByText('已取消')).toBeInTheDocument()

    // 验证操作按钮
    expect(screen.getByText('编辑订单')).toBeInTheDocument()
    expect(screen.getByText('下载订单报告')).toBeInTheDocument()
    expect(screen.getByText('分享订单')).toBeInTheDocument()
  })

  test('状态变更功能', () => {
    renderWithQueryClient(<OrderDetail />)

    // 初始状态为"进行中"
    const inProgressButton = screen.getByRole('button', { name: '进行中' })
    expect(inProgressButton).toHaveClass('bg-green-100')

    // 点击"已完成"状态
    const completedButton = screen.getByText('已完成')
    fireEvent.click(completedButton)

    // 验证状态变更（通过控制台日志验证）
  })

  test('添加备注功能', () => {
    renderWithQueryClient(<OrderDetail />)

    const textarea = screen.getByPlaceholderText('请输入备注内容...')
    const saveButton = screen.getByText('保存备注')

    // 输入备注内容
    fireEvent.change(textarea, { target: { value: '这是一个测试备注' } })
    expect(textarea).toHaveValue('这是一个测试备注')

    // 点击保存按钮
    fireEvent.click(saveButton)
  })

  test('查看详细打卡记录', () => {
    renderWithQueryClient(<OrderDetail />)

    const viewDetailButton = screen.getByText('查看详细打卡记录')
    fireEvent.click(viewDetailButton)
  })

  test('视频播放和下载按钮', () => {
    renderWithQueryClient(<OrderDetail />)

    const playButtons = screen.getAllByText('播放')
    const downloadButtons = screen.getAllByText('下载')

    expect(playButtons.length).toBeGreaterThan(0)
    expect(downloadButtons.length).toBeGreaterThan(0)

    // 点击第一个播放按钮
    fireEvent.click(playButtons[0])
    // 点击第一个下载按钮
    fireEvent.click(downloadButtons[0])
  })
})