import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.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_quarantine_row.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final fs = Theme.of(context).extension<FabledSwordTheme>()!;
    // #402 wire-up: any quarantine event (flag from a user / admin
    // resolve / file delete / lidarr delete) refreshes the admin queue.
    ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
      final e = next.asData?.value;
      if (e == null) return;
      if (e.kind.startsWith('quarantine.')) {
        ref.invalidate(adminQuarantineProvider);
      }
    });
    final items = ref.watch(adminQuarantineProvider);
    return Scaffold(
      backgroundColor: fs.obsidian,
      appBar: AppBar(
        backgroundColor: fs.obsidian,
        elevation: 0,
        title: Text('Quarantine', style: TextStyle(color: fs.parchment)),
        actions: const [MainAppBarActions(currentRoute: '/admin/quarantine')],
      ),
      body: SafeArea(
        child: items.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 quarantined tracks.',
                    style: TextStyle(color: fs.ash)),
              );
            }
            final notifier = ref.read(adminQuarantineProvider.notifier);
            return RefreshIndicator(
              onRefresh: () async =>
                  ref.refresh(adminQuarantineProvider.future),
              child: ListView.builder(
                itemCount: rows.length,
                itemBuilder: (_, i) => AdminQuarantineRow(
                  key: Key('admin_quarantine_row_${rows[i].trackId}'),
                  item: rows[i],
                  onResolve: () => notifier.resolve(rows[i].trackId),
                  onDeleteFile: () => notifier.deleteFile(rows[i].trackId),
                  onDeleteViaLidarr: () =>
                      notifier.deleteViaLidarr(rows[i].trackId),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
