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

class AdminRequestsView extends StatelessWidget {
  const AdminRequestsView({super.key});
  static const Color terminalGreen = Color(0xFF00FF00);

  // Function to delete a request after Sage has sent the key
  Future<void> _purgeSignal(String docId) async {
    await FirebaseFirestore.instance.collection('requests').doc(docId).delete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text("INCOMING_SIGNALS"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, size: 16),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection('requests')
            .orderBy('timestamp', descending: true)
            .snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: terminalGreen));

          final reqs = snapshot.data!.docs;
          if (reqs.isEmpty) return const Center(child: Text("NO_SIGNALS_DETECTED", style: TextStyle(color: Colors.white10)));

          return ListView.builder(
            padding: const EdgeInsets.all(10),
            itemCount: reqs.length,
            itemBuilder: (context, index) {
              final r = reqs[index].data() as Map<String, dynamic>;
              final String docId = reqs[index].id;

              // Handle different labels for PayPal vs Free Requests
              String sender = r['origin'] == 'FREE_REQUEST'
                  ? (r['name'] ?? "ANON")
                  : "PAYPAL_INVESTOR";
              String contact = r['origin'] == 'FREE_REQUEST'
                  ? (r['contact'] ?? "NO_CONTACT")
                  : (r['id'] ?? "NO_ID");

              return Container(
                margin: const EdgeInsets.symmetric(vertical: 5),
                decoration: BoxDecoration(
                  border: Border.all(color: terminalGreen.withValues(alpha: 0.2)),
                ),
                child: ListTile(
                  title: Text(contact, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                  subtitle: Text(
                    "SENDER: $sender\nTYPE: ${r['origin']}\nTIER_REQ: LVL_0${r['requestedTier'] ?? '?'}",
                    style: const TextStyle(fontSize: 10, color: Colors.grey),
                  ),
                  trailing: IconButton(
                    icon: const Icon(Icons.close, color: Colors.red, size: 20),
                    onPressed: () => _purgeSignal(docId),
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}