import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'react-redux'
import { MemoryRouter } from 'react-router-dom'
import { configureStore } from '@reduxjs/toolkit'
import authReducer from '../store/slices/authSlice'
import UserListPage from '../pages/usr/UserListPage'

vi.mock('../api/usr', () => ({
  getStaffs: vi.fn().mockResolvedValue([]),
  getPermissionGroups: vi.fn().mockResolvedValue([]),
  createUser: vi.fn(),
  getUserList: vi.fn().mockResolvedValue({ total: 0, page: 1, pageSize: 20, list: [] }),
  updateUser: vi.fn().mockResolvedValue({ userId: 'u1', username: 'alice', updatedAt: '2026-05-08T10:00:00' })
}))

vi.mock('../api/request', () => ({
  default: { get: vi.fn(), post: vi.fn() }
}))

function makeStore(userType: string) {
  const store = configureStore({ reducer: { auth: authReducer } })
  store.dispatch({
    type: 'auth/setCredentials',
    payload: {
      accessToken: 'test-token',
      refreshToken: 'test-refresh',
      userInfo: { userId: 'u1', username: 'admin', userType, language: '中文', brandId: 'b1' }
    }
  })
  return store
}

function renderPage(userType: string) {
  const store = makeStore(userType)
  return render(
    <Provider store={store}>
      <MemoryRouter>
        <UserListPage />
      </MemoryRouter>
    </Provider>
  )
}

describe('UserListPage', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('superAdmin_seesNewButton', () => {
    renderPage('超级管理员')
    expect(screen.getByRole('button', { name: /新\s*增/ })).toBeInTheDocument()
  })

  it('normalUser_doesNotSeeNewButton', () => {
    renderPage('普通用户')
    expect(screen.queryByRole('button', { name: /新\s*增/ })).not.toBeInTheDocument()
  })

  it('clickNewButton_opensDrawer', async () => {
    renderPage('超级管理员')
    await userEvent.click(screen.getByRole('button', { name: /新\s*增/ }))
    await waitFor(() => expect(screen.getByText('新增用户')).toBeInTheDocument())
  })

  it('initialLoad_rendersTableRows', async () => {
    const { getUserList } = await import('../api/usr')
    vi.mocked(getUserList).mockResolvedValueOnce({
      total: 1, page: 1, pageSize: 20,
      list: [{
        sId: 'u1', sUsername: 'alice', sUserCode: 'UC001', sUserType: '普通用户',
        sLanguage: '中文', bIsDisabled: 0, tLastLoginDate: null,
        sCreatorUsername: 'admin', tCreateDate: '2026-01-01T00:00:00',
        sStaffName: '张三', sDepartment: '研发部'
      }]
    })
    renderPage('超级管理员')
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument())
    expect(screen.getByText('张三')).toBeInTheDocument()
  })

  it('searchButton_callsGetUserList', async () => {
    const { getUserList } = await import('../api/usr')
    renderPage('超级管理员')
    await userEvent.click(screen.getByRole('button', { name: /搜\s*索|搜索/ }))
    await waitFor(() => expect(vi.mocked(getUserList)).toHaveBeenCalledTimes(2))
  })

  it('editMode_submit_callsUpdateUser', async () => {
    const { getUserList, updateUser } = await import('../api/usr')
    vi.mocked(getUserList).mockResolvedValue({
      total: 1, page: 1, pageSize: 20,
      list: [{
        sId: 'u1', sUsername: 'alice', sUserCode: 'UC001', sUserType: '普通用户',
        sLanguage: '中文', bIsDisabled: 0, tLastLoginDate: null,
        sCreatorUsername: 'admin', tCreateDate: '2026-01-01T00:00:00',
        sStaffName: null, sDepartment: null
      }]
    })
    renderPage('超级管理员')
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /修改/ }))
    await waitFor(() => expect(screen.getByText('修改用户')).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /确\s*认/ }))
    await waitFor(() => expect(vi.mocked(updateUser)).toHaveBeenCalledTimes(1))
  })
})
