import { describe, it, expect } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConfigProvider } from 'antd';
import { configureStore } from '@reduxjs/toolkit';
import authReducer, { setSession } from '../../store/slices/authSlice';
import UsersListPage from './UsersListPage';

function makeStore() {
  const store = configureStore({ reducer: { auth: authReducer } });
  store.dispatch(
    setSession({
      accessToken: 'jwt',
      userInfo: {
        userId: 2,
        username: 'admin',
        userType: 'SUPER_ADMIN',
        language: 'zh-CN',
        companyCode: 'HQ',
      },
    }),
  );
  return store;
}

function renderPage() {
  return render(
    <Provider store={makeStore()}>
      <ConfigProvider>
        <MemoryRouter initialEntries={['/users']}>
          <Routes>
            <Route path="/users" element={<UsersListPage />} />
            <Route path="/users/new" element={<div data-testid="users-new">NEW</div>} />
            <Route path="/users/:userId" element={<div data-testid="users-detail">DETAIL</div>} />
          </Routes>
        </MemoryRouter>
      </ConfigProvider>
    </Provider>,
  );
}

describe('UsersListPage', () => {
  it('mount → list 加载并渲染表格行', async () => {
    renderPage();
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
    // "admin" 在两处出现（username 与 createdBy），用 getAllByText
    expect(screen.getAllByText('admin').length).toBeGreaterThanOrEqual(1);
    expect(screen.getByText('bob_deleted')).toBeInTheDocument();
  });

  it('点击新增 → 导航到 /users/new', async () => {
    renderPage();
    const user = userEvent.setup();
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
    await user.click(screen.getByTestId('toolbar-add'));
    expect(await screen.findByTestId('users-new')).toBeInTheDocument();
  });

  it('点击行 → 导航到 /users/:userId', async () => {
    renderPage();
    const user = userEvent.setup();
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
    await user.click(screen.getByText('alice'));
    expect(await screen.findByTestId('users-detail')).toBeInTheDocument();
  });

  it('刷新按钮可调用', async () => {
    renderPage();
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
    const user = userEvent.setup();
    await user.click(screen.getByTestId('toolbar-refresh'));
    // 重新查询后列表仍存在
    await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument());
  });
});
