/**
 * EmploymentPage页面测试
 * 使用真实的React Query进行集成测试
 */
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import EmploymentPage from '@/pages/EmploymentPage/EmploymentPage'

// Mock Taro
jest.mock('@tarojs/taro', () => ({
  showToast: jest.fn(),
  navigateBack: jest.fn()
}))

// Mock API client
jest.mock('@/api', () => ({
  talentEmploymentClient: {
    employment: {
      status: {
        $get: jest.fn()
      },
      'salary-records': {
        $get: jest.fn()
      },
      history: {
        $get: jest.fn()
      }
    }
  }
}))

// Mock auth hooks
jest.mock('@d8d/rencai-auth-ui/hooks', () => ({
  useRequireAuth: jest.fn()
}))

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

const { talentEmploymentClient } = require('@/api')
const Taro = require('@tarojs/taro')
const { useRequireAuth } = require('@d8d/rencai-auth-ui/hooks')

const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: { retry: false, staleTime: Infinity },
    mutations: { retry: false }
  }
})

const renderWithQueryClient = (component: React.ReactElement) => {
  const queryClient = createTestQueryClient()
  return render(
    <QueryClientProvider client={queryClient}>
      {component}
    </QueryClientProvider>
  )
}

// Mock数据
const mockCurrentStatus = {
  companyName: '测试科技有限公司',
  orderId: 1,
  orderName: '数据标注员',
  positionName: '数据标注员',
  joinDate: '2023-08-15',
  workStatus: 'working',
  salaryLevel: 4800,
  actualStartDate: '2023-08-15'
}

const mockSalaryRecords = {
  data: [
    {
      orderId: 1,
      orderName: '数据标注员',
      companyName: '测试科技有限公司',
      salaryAmount: 4800,
      joinDate: '2023-08-15',
      month: '2023-11'
    },
    {
      orderId: 1,
      orderName: '数据标注员',
      companyName: '测试科技有限公司',
      salaryAmount: 4800,
      joinDate: '2023-08-15',
      month: '2023-10'
    }
  ],
  total: 2
}

const mockEmploymentHistory = {
  data: [
    {
      orderId: 1,
      orderName: '数据标注员',
      companyName: '测试科技有限公司',
      positionName: '数据标注员',
      joinDate: '2023-08-15',
      leaveDate: null,
      workStatus: 'working',
      salaryLevel: 4800
    }
  ],
  total: 1
}

describe('EmploymentPage', () => {
  beforeEach(() => {
    jest.clearAllMocks()
    useRequireAuth.mockReturnValue(undefined)
  })

  describe('页面加载', () => {
    it('应该显示加载状态', async () => {
      // Mock API为pending状态以测试loading
      talentEmploymentClient.employment.status.$get.mockImplementation(
        () => new Promise(() => {})
      )
      talentEmploymentClient.employment['salary-records'].$get.mockImplementation(
        () => new Promise(() => {})
      )
      talentEmploymentClient.employment.history.$get.mockImplementation(
        () => new Promise(() => {})
      )

      renderWithQueryClient(<EmploymentPage />)

      // 三个组件都显示加载中
      expect(screen.getAllByText('加载中...')).toHaveLength(3)
    })

    it('应该成功加载并显示数据', async () => {
      talentEmploymentClient.employment.status.$get.mockResolvedValue({
        ok: true,
        json: async () => mockCurrentStatus
      })

      talentEmploymentClient.employment['salary-records'].$get.mockResolvedValue({
        ok: true,
        json: async () => mockSalaryRecords
      })

      talentEmploymentClient.employment.history.$get.mockResolvedValue({
        ok: true,
        json: async () => mockEmploymentHistory
      })

      renderWithQueryClient(<EmploymentPage />)

      await waitFor(() => {
        expect(screen.getByText('当前就业状态')).toBeInTheDocument()
        expect(screen.getByText('薪资记录')).toBeInTheDocument()
        expect(screen.getByText('就业历史')).toBeInTheDocument()
      })
    })

    it('应该显示当前就业状态数据', async () => {
      talentEmploymentClient.employment.status.$get.mockResolvedValue({
        ok: true,
        json: async () => mockCurrentStatus
      })

      talentEmploymentClient.employment['salary-records'].$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      talentEmploymentClient.employment.history.$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      renderWithQueryClient(<EmploymentPage />)

      await waitFor(() => {
        expect(screen.getByText('测试科技有限公司')).toBeInTheDocument()
      })
    })
  })

  describe('Navbar集成', () => {
    it('应该渲染带返回按钮的Navbar', async () => {
      talentEmploymentClient.employment.status.$get.mockResolvedValue({
        ok: true,
        json: async () => mockCurrentStatus
      })

      talentEmploymentClient.employment['salary-records'].$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      talentEmploymentClient.employment.history.$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      renderWithQueryClient(<EmploymentPage />)

      const navbar = screen.getByTestId('navbar')
      expect(navbar).toBeInTheDocument()
      expect(navbar).toHaveAttribute('data-title', '就业信息')
      expect(navbar).toHaveAttribute('data-left-icon', 'i-heroicons-chevron-left-20-solid')
      expect(navbar).toHaveAttribute('data-left-text', '返回')
    })
  })

  describe('认证检查', () => {
    it('应该调用useRequireAuth检查登录状态', async () => {
      talentEmploymentClient.employment.status.$get.mockResolvedValue({
        ok: true,
        json: async () => mockCurrentStatus
      })

      talentEmploymentClient.employment['salary-records'].$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      talentEmploymentClient.employment.history.$get.mockResolvedValue({
        ok: true,
        json: async () => ({ data: [], total: 0 })
      })

      renderWithQueryClient(<EmploymentPage />)

      expect(useRequireAuth).toHaveBeenCalled()
    })
  })
})
