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_requests_screen.dart';
import 'package:minstrel/auth/auth_provider.dart';
import 'package:minstrel/models/admin_request.dart';
import 'package:minstrel/models/admin_user.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 _StubRequests extends AdminRequestsController {
  _StubRequests(this._initial);
  final List<AdminRequest> _initial;
  @override
  Future<List<AdminRequest>> build() async => _initial;
}

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

const _row = AdminRequest(
  id: 'r1',
  userId: 'user-uuid-1',
  status: 'pending',
  kind: 'album',
  artistName: 'Some Artist',
  albumTitle: 'Test Album',
  trackTitle: null,
  requestedAt: '2026-05-08T00:00:00Z',
  decidedAt: null,
  notes: null,
  importedAlbumCount: 0,
  importedTrackCount: 0,
);

const _alice = AdminUser(
  id: 'user-uuid-1',
  username: 'alice',
  displayName: null,
  isAdmin: false,
  autoApproveRequests: false,
  createdAt: '2026-05-01T00:00:00Z',
);

Widget _harness({
  required List<AdminRequest> requests,
  required List<AdminUser> users,
}) =>
    ProviderScope(
      overrides: [
        authControllerProvider.overrideWith(() => _StubAuth()),
        adminRequestsProvider.overrideWith(() => _StubRequests(requests)),
        adminUsersProvider.overrideWith(() => _StubUsers(users)),
      ],
      child: MaterialApp(
        theme: buildThemeData(),
        home: const AdminRequestsScreen(),
      ),
    );

void main() {
  testWidgets('renders empty state when no requests', (t) async {
    await t.pumpWidget(_harness(requests: const [], users: const []));
    await t.pumpAndSettle();
    expect(find.text('No pending requests.'), findsOneWidget);
  });

  testWidgets('renders row with display name + joined requester username',
      (t) async {
    await t.pumpWidget(_harness(requests: const [_row], users: const [_alice]));
    await t.pumpAndSettle();
    expect(find.byKey(const Key('admin_request_row_r1')), findsOneWidget);
    expect(find.text('Test Album'), findsOneWidget);
    expect(find.textContaining('requested by alice'), findsOneWidget);
  });

  testWidgets('falls back to uuid prefix when username unknown', (t) async {
    await t.pumpWidget(_harness(requests: const [_row], users: const []));
    await t.pumpAndSettle();
    expect(find.textContaining('requested by user-uui'), findsOneWidget);
  });
}
