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

import '../models/admin_user.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'admin_providers.dart';
import 'widgets/admin_request_row.dart';

class AdminRequestsScreen extends ConsumerWidget {
  const AdminRequestsScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final fs = Theme.of(context).extension<FabledSwordTheme>()!;
    // #402 wire-up: invalidate the admin requests list when a user
    // creates/cancels/admin approves/rejects/reconciler completes —
    // request.status_changed covers all of them.
    ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
      final e = next.asData?.value;
      if (e?.kind == 'request.status_changed') {
        ref.invalidate(adminRequestsProvider);
      }
    });
    final requests = ref.watch(adminRequestsProvider);
    // Best-effort lookup for requester usernames. If the users provider
    // hasn't loaded yet, valueOrNull is null and rows fall back to the
    // UUID prefix; no blocking spinner.
    final users = ref.watch(adminUsersProvider).value ?? const <AdminUser>[];
    final usersById = {for (final u in users) u.id: u};

    return Scaffold(
      backgroundColor: fs.obsidian,
      appBar: AppBar(
        backgroundColor: fs.obsidian,
        elevation: 0,
        title: Text('Requests', style: TextStyle(color: fs.parchment)),
        actions: const [MainAppBarActions(currentRoute: '/admin/requests')],
      ),
      body: SafeArea(
        child: requests.when(
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (e, _) =>
              Center(child: Text('$e', style: TextStyle(color: fs.error))),
          data: (rows) {
            if (rows.isEmpty) {
              return Center(
                child: Text('No pending requests.',
                    style: TextStyle(color: fs.ash)),
              );
            }
            final notifier = ref.read(adminRequestsProvider.notifier);
            return RefreshIndicator(
              onRefresh: () async =>
                  ref.refresh(adminRequestsProvider.future),
              child: ListView.builder(
                itemCount: rows.length,
                itemBuilder: (_, i) {
                  final req = rows[i];
                  final user = usersById[req.userId];
                  final display = user?.username ??
                      (req.userId.length >= 8
                          ? req.userId.substring(0, 8)
                          : req.userId);
                  return AdminRequestRow(
                    key: Key('admin_request_row_${req.id}'),
                    request: req,
                    requesterDisplay: display,
                    onApprove: () => notifier.approve(req.id),
                    onReject: () => notifier.reject(req.id),
                  );
                },
              ),
            );
          },
        ),
      ),
    );
  }
}
