import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:minstrel/admin/admin_providers.dart';
import 'package:minstrel/admin/admin_users_screen.dart';
import 'package:minstrel/auth/auth_provider.dart';
import 'package:minstrel/models/admin_user.dart';
import 'package:minstrel/models/invite.dart';
import 'package:minstrel/models/user.dart';
import 'package:minstrel/theme/theme_data.dart';

class _StubAuth extends AuthController {
  @override
  Future<User?> build() async =>
      const User(id: 'u1', username: 'admin', isAdmin: true);
}

class _StubUsers extends AdminUsersController {
  _StubUsers(this._initial);
  final List<AdminUser> _initial;
  @override
  Future<List<AdminUser>> build() async => _initial;
}

class _StubInvites extends AdminInvitesController {
  _StubInvites(this._initial);
  final List<Invite> _initial;
  @override
  Future<List<Invite>> build() async => _initial;
}

const _userRow = AdminUser(
  id: 'u2',
  username: 'alice',
  displayName: null,
  isAdmin: false,
  autoApproveRequests: true,
  createdAt: '2026-05-01T00:00:00Z',
);

const _inviteRow = Invite(
  token: 'INV-ABC123',
  invitedBy: 'u1',
  note: 'for alice',
  createdAt: '2026-05-08T00:00:00Z',
  expiresAt: '2026-05-09T00:00:00Z',
);

Widget _harness({
  required List<AdminUser> users,
  required List<Invite> invites,
}) =>
    ProviderScope(
      overrides: [
        authControllerProvider.overrideWith(() => _StubAuth()),
        adminUsersProvider.overrideWith(() => _StubUsers(users)),
        adminInvitesProvider.overrideWith(() => _StubInvites(invites)),
      ],
      child: MaterialApp(
        theme: buildThemeData(),
        home: const AdminUsersScreen(),
      ),
    );

void main() {
  testWidgets('renders user rows with badges', (t) async {
    await t.pumpWidget(_harness(users: const [_userRow], invites: const []));
    await t.pumpAndSettle();
    expect(find.byKey(const Key('admin_user_row_u2')), findsOneWidget);
    expect(find.text('alice'), findsOneWidget);
    expect(find.text('auto-approve'), findsOneWidget);
  });

  testWidgets('renders invite rows + Generate button', (t) async {
    await t.pumpWidget(_harness(users: const [], invites: const [_inviteRow]));
    await t.pumpAndSettle();
    expect(find.byKey(const Key('invite_row_INV-ABC123')), findsOneWidget);
    expect(find.byKey(const Key('invite_generate_button')), findsOneWidget);
    expect(find.textContaining('for alice'), findsOneWidget);
  });
}
