import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/api/client';
import { UsersAdminPage } from '@/pages/UsersAdminPage';
import { renderWithProviders } from './utils';
import type { User } from '@/api/types';

// Mock useAuth so the page sees a logged-in admin without hydrating from network.
vi.mock('@/hooks/useAuth', () => ({
  useAuth: () => ({
    user: { id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' } as User,
    status: 'authenticated',
    login: vi.fn(),
    logout: vi.fn(),
    isAdmin: true,
    isRedteam: false,
    isSoc: false,
    canEditEngagements: true,
  }),
}));

const USERS: User[] = [
  { id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' },
  { id: 2, username: 'bob', role: 'redteam', created_at: '2026-02-01' },
  { id: 3, username: 'carol', role: 'soc', created_at: '2026-03-01' },
];

describe('UsersAdminPage', () => {
  let mock: MockAdapter;

  beforeEach(() => {
    mock = new MockAdapter(apiClient);
    mock.onGet('/users').reply(200, USERS);
  });

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

  it('renders the list of users from the API', async () => {
    renderWithProviders(<UsersAdminPage />);
    expect(await screen.findByText('alice')).toBeInTheDocument();
    expect(screen.getByText('bob')).toBeInTheDocument();
    expect(screen.getByText('carol')).toBeInTheDocument();
  });

  it('creates a user via POST /users and refreshes the list', async () => {
    const newUser: User = { id: 4, username: 'dan', role: 'soc', created_at: '2026-04-01' };
    const postSpy = vi.fn().mockReturnValue([201, newUser]);
    mock.onPost('/users').reply((config) => postSpy(JSON.parse(config.data)));

    const user = userEvent.setup();
    renderWithProviders(<UsersAdminPage />);

    await screen.findByText('alice');

    await user.type(screen.getByLabelText(/^nom d'utilisateur/i), 'dan');
    await user.type(screen.getByLabelText(/^mot de passe/i), 'sup3rs4fe!');
    // role default is 'redteam'; switch to 'soc' to match newUser
    await user.selectOptions(screen.getByTestId('new-role-select'), 'soc');

    // After POST, hooks invalidate and the list refetches → return the new list
    mock.onGet('/users').reply(200, [...USERS, newUser]);

    await user.click(screen.getByRole('button', { name: /^créer$/i }));

    await waitFor(() => {
      expect(postSpy).toHaveBeenCalledWith({
        username: 'dan',
        password: 'sup3rs4fe!',
        role: 'soc',
      });
    });
    expect(await screen.findByText('dan')).toBeInTheDocument();
  });

  it('opens the password reset form for the row that was clicked (fragment-key regression guard)', async () => {
    const user = userEvent.setup();
    renderWithProviders(<UsersAdminPage />);

    await screen.findByText('bob');

    // The "Reset password" button for bob lives in bob's row.
    const bobRow = screen.getByText('bob').closest('tr');
    expect(bobRow).not.toBeNull();
    await user.click(within(bobRow as HTMLElement).getByRole('button', { name: /réinitialiser le mot de passe/i }));

    // The reset form for bob (and bob only) must appear.
    expect(await screen.findByLabelText(/nouveau mot de passe pour bob/i)).toBeInTheDocument();
    expect(screen.queryByLabelText(/nouveau mot de passe pour carol/i)).toBeNull();
    expect(screen.queryByLabelText(/nouveau mot de passe pour alice/i)).toBeNull();
  });

  it('disables the delete button on the current user own row', async () => {
    renderWithProviders(<UsersAdminPage />);
    await screen.findByText('alice');

    const aliceRow = screen.getByText('alice').closest('tr') as HTMLElement;
    const bobRow = screen.getByText('bob').closest('tr') as HTMLElement;

    expect(within(aliceRow).getByRole('button', { name: /supprimer/i })).toBeDisabled();
    expect(within(bobRow).getByRole('button', { name: /supprimer/i })).toBeEnabled();
  });
});
