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 Administer from './Administer';

// Mock axios
jest.mock('axios');

// Mock localStorage
const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
};
global.localStorage = localStorageMock;

describe('Administer Component', () => {
  beforeEach(() => {
    localStorageMock.getItem.mockReturnValue('test-token');
    jest.clearAllMocks();
  });

  const mockUsers = [
    {
      username: 'user1',
      authority: 'USER',
      registTime: '2023-01-01T00:00:00',
      lastLogin: '2023-05-01T00:00:00',
      upload: 1000,
      download: 500,
      shareRate: 2.0,
      magicPoints: 100
    },
    {
      username: 'admin1',
      authority: 'ADMIN',
      registTime: '2023-01-15T00:00:00',
      lastLogin: '2023-05-10T00:00:00',
      upload: 5000,
      download: 1000,
      shareRate: 5.0,
      magicPoints: 500
    }
  ];

  const mockDiscounts = [
    {
      id: 1,
      name: '五一活动',
      discountType: 'FREE',
      startTime: '2023-05-01T00:00:00',
      endTime: '2023-05-07T23:59:59',
      createTime: '2023-04-25T10:00:00',
      status: '已过期'
    },
    {
      id: 2,
      name: '端午节活动',
      discountType: 'HALF',
      startTime: '2023-06-10T00:00:00',
      endTime: '2023-06-15T23:59:59',
      createTime: '2023-05-30T10:00:00',
      status: '已过期'
    }
  ];

  const mockCurrentDiscount = {
    id: 3,
    name: '国庆活动',
    discountType: 'DOUBLE',
    startTime: '2023-10-01T00:00:00',
    endTime: '2023-10-07T23:59:59',
    createTime: '2023-09-25T10:00:00',
    status: '进行中'
  };

  const renderAdminister = () => {
    return render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );
  };

  test('renders Administer component with user tab by default', async () => {
    axios.get.mockResolvedValueOnce({
      data: {
        code: 200,
        data: { data: mockUsers }
      }
    });

    renderAdminister();

    expect(screen.getByText('系统管理')).toBeInTheDocument();
    expect(screen.getByText('用户管理')).toBeInTheDocument();
    expect(screen.getByText('折扣管理')).toBeInTheDocument();

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

  test('switches between user and discount tabs', async () => {
    axios.get
      .mockResolvedValueOnce({
        data: {
          code: 200,
          data: { data: mockUsers }
        }
      })
      .mockResolvedValueOnce({
        data: {
          code: 200,
          data: { data: mockDiscounts }
        }
      })
      .mockResolvedValueOnce({
        data: {
          code: 200,
          data: { data: mockCurrentDiscount }
        }
      });

    renderAdminister();

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

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

    await waitFor(() => {
      expect(screen.getByText('五一活动')).toBeInTheDocument();
    });
    
    expect(screen.getByText('国庆活动')).toBeInTheDocument();
  });

 

  test('changes user authority', async () => {
    axios.get.mockResolvedValueOnce({
      data: {
        code: 200,
        data: { data: mockUsers }
      }
    });
    axios.put.mockResolvedValueOnce({
      data: {
        code: 200,
        message: '修改用户权限成功'
      }
    });

    renderAdminister();

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

    const selectElement = screen.getAllByRole('combobox')[0];
    fireEvent.change(selectElement, { target: { value: 'ADMIN' } });

    await waitFor(() => {
      expect(axios.put).toHaveBeenCalled();
    });
    
    expect(axios.put).toHaveBeenCalledWith(
      expect.stringContaining('/user/changeAuthority'),
      {
        changeUsername: 'user1',
        authority: 'ADMIN'
      },
      expect.any(Object)
    );
  });



  test('shows error messages', async () => {
    axios.get.mockRejectedValueOnce(new Error('Network Error'));

    renderAdminister();

    await waitFor(() => {
      expect(screen.getByText(/获取用户列表失败/)).toBeInTheDocument();
    });
  });
});