import React from 'react';
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import '@testing-library/jest-dom';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import Administer from './Administer';

describe('Administer Component', () => {
  let mock;

  beforeAll(() => {
    mock = new MockAdapter(axios);
    localStorage.setItem('token', 'test-token');
  });

  afterEach(() => {
    mock.reset();
  });

  afterAll(() => {
    mock.restore();
  });

  test('renders user management tab by default', async () => {
    mock.onGet('/user/allUser').reply(200, {
      code: 200,
      data: { data: [] }
    });

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    expect(screen.getByText('用户管理')).toBeInTheDocument();
    expect(screen.getByText('折扣管理')).toBeInTheDocument();
    expect(screen.getByText('公告管理')).toBeInTheDocument();
  });

  test('fetches and displays users', async () => {
    const mockUsers = [
      {
        username: 'testuser',
        authority: 'USER',
        registTime: '2023-01-01',
        lastLogin: '2023-05-01',
        upload: 1000,
        download: 500,
        shareRate: 2.0,
        magicPoints: 100
      }
    ];

    mock.onGet('/user/allUser').reply(200, {
      code: 200,
      data: { data: mockUsers }
    });

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    await waitFor(() => {
      expect(screen.getByText('testuser')).toBeInTheDocument();
    });
  });

  test('handles user search', async () => {
    const mockUsers = [
      {
        username: 'searchuser',
        authority: 'USER'
      }
    ];

    mock.onGet('/user/searchUser').reply(200, {
      code: 200,
      data: { data: mockUsers }
    });

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    fireEvent.change(screen.getByPlaceholderText('输入用户名搜索'), {
      target: { value: 'search' }
    });
    fireEvent.click(screen.getByText('搜索'));

    await waitFor(() => {
      expect(screen.getByText('searchuser')).toBeInTheDocument();
    });
  });

  test('switches between tabs', async () => {
    mock.onGet('/user/allUser').reply(200, {
      code: 200,
      data: { data: [] }
    });

    mock.onGet('/discount/all').reply(200, {
      code: 200,
      data: { data: [] }
    });

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    fireEvent.click(screen.getByText('折扣管理'));

    await waitFor(() => {
      expect(screen.getByText('添加新折扣')).toBeInTheDocument();
    });
  });
});