import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { SettingsRolesPage } from '@/pages/SettingsRoles';

vi.mock('@/components/ui/Toast', () => ({
  useToast: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
}));

const { mockRoles, forceUpdateRef } = vi.hoisted(() => {
  const forceUpdateRef: { current: () => void } = { current: () => {} };
  const mockRoles = [
    { id: '1', name: 'Administrator', permissions: { all: true }, denied_permissions: [], field_permissions: {} },
    { id: '2', name: 'Mitarbeiter', permissions: { 'companies.read': true, 'contacts.read': true }, denied_permissions: [], field_permissions: {} },
    { id: '3', name: 'Gast', permissions: {}, denied_permissions: [], field_permissions: {} },
  ];
  return { mockRoles, forceUpdateRef };
});

vi.mock('@/api/hooks', () => ({
  useRoles: () => {
    const [, setUpdate] = React.useState({});
    forceUpdateRef.current = () => setUpdate({});
    return {
      data: {
        items: mockRoles.map(r => ({ ...r })),
        total: mockRoles.length,
      },
      isLoading: false,
      isError: false,
      error: null,
      refetch: () => forceUpdateRef.current(),
    };
  },
  useCreateRole: () => ({
    mutateAsync: async (data: any) => {
      const newRole = { id: String(mockRoles.length + 1), name: data.name, permissions: data.permissions || {}, denied_permissions: data.denied_permissions || [], field_permissions: data.field_permissions || {} };
      mockRoles.push(newRole);
      forceUpdateRef.current();
      return newRole;
    },
    isPending: false,
  }),
  useUpdateRole: () => ({
    mutateAsync: async (payload: any) => {
      const idx = mockRoles.findIndex(r => r.id === payload.id);
      if (idx >= 0) {
        mockRoles[idx] = { ...mockRoles[idx], ...payload.data };
      }
      forceUpdateRef.current();
      return undefined;
    },
    isPending: false,
  }),
  useDeleteRole: () => ({ mutateAsync: vi.fn().mockResolvedValue(undefined), isPending: false }),
  usePermissions: () => ({
    data: {
      all: [
        { key: 'companies.read', label: 'Firmen lesen', category: 'system' },
        { key: 'companies.write', label: 'Firmen schreiben', category: 'system' },
        { key: 'contacts.read', label: 'Kontakte lesen', category: 'system' },
        { key: 'contacts.write', label: 'Kontakte schreiben', category: 'system' },
      ],
      field_definitions: [],
    },
    isLoading: false,
  }),
}));

describe('SettingsRolesPage', () => {
  it('renders roles page', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    expect(screen.getByTestId('settings-roles-page')).toBeInTheDocument();
  });

  it('renders role editor with create button', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    expect(screen.getByTestId('create-role-btn')).toBeInTheDocument();
  });

  it('renders existing roles with permissions', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    expect(screen.getByText('Administrator')).toBeInTheDocument();
    expect(screen.getByText('Mitarbeiter')).toBeInTheDocument();
    expect(screen.getByText('Gast')).toBeInTheDocument();
  });

  it('renders edit buttons for each role', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    expect(screen.getByTestId('edit-role-1')).toBeInTheDocument();
    expect(screen.getByTestId('edit-role-2')).toBeInTheDocument();
    expect(screen.getByTestId('edit-role-3')).toBeInTheDocument();
  });

  it('opens create role modal when create button clicked', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('create-role-btn'));
    expect(screen.getByTestId('create-role-form')).toBeInTheDocument();
  });

  it('create role form has role name input', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('create-role-btn'));
    expect(screen.getByTestId('new-role-name')).toBeInTheDocument();
  });

  it('create role form has permission checkboxes', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('create-role-btn'));
    const checkboxes = screen.getAllByRole('checkbox');
    expect(checkboxes.length).toBeGreaterThan(0);
  });

  it('can enter role name and save', async () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('create-role-btn'));
    const nameInput = screen.getByTestId('new-role-name');
    fireEvent.change(nameInput, { target: { value: 'Vertrieb' } });
    fireEvent.click(screen.getByTestId('save-role-btn'));
    await waitFor(() => {
      expect(screen.getByText('Vertrieb')).toBeInTheDocument();
    });
  });

  it('opens edit modal for existing role', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('edit-role-1'));
    expect(screen.getByTestId('edit-role-form')).toBeInTheDocument();
  });

  it('can update role name via edit modal', async () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    fireEvent.click(screen.getByTestId('edit-role-1'));
    const inputs = screen.getByTestId('edit-role-form').querySelectorAll('input:not([type="checkbox"])');
    fireEvent.change(inputs[0], { target: { value: 'Super Admin' } });
    fireEvent.click(screen.getByTestId('update-role-btn'));
    await waitFor(() => {
      expect(screen.getByText('Super Admin')).toBeInTheDocument();
    });
  });

  it('renders permission badges for roles', () => {
    render(<MemoryRouter><SettingsRolesPage /></MemoryRouter>);
    expect(screen.getAllByText(/Firmen lesen/).length).toBeGreaterThan(0);
    expect(screen.getAllByText(/Kontakte lesen/).length).toBeGreaterThan(0);
  });
});
