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

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

  // Function to upgrade/downgrade user tier
  Future<void> _updateTier(String uid, int newTier) async {
    await FirebaseFirestore.instance.collection('users').doc(uid).update({
      'tier': newTier,
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text("USER_DATABASE"),
        centerTitle: true,
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('users').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: terminalGreen));

          final users = snapshot.data!.docs;

          return ListView.builder(
            itemCount: users.length,
            padding: const EdgeInsets.all(10),
            itemBuilder: (context, index) {
              final userData = users[index].data() as Map<String, dynamic>;
              final String uid = users[index].id;
              final int currentTier = userData['tier'] ?? 1;

              return Container(
                margin: const EdgeInsets.symmetric(vertical: 5),
                decoration: BoxDecoration(
                  border: Border.all(color: terminalGreen.withValues(alpha: 0.2)),
                ),
                child: ListTile(
                  title: Text(userData['displayName'] ?? "UNKNOWN_ID", style: const TextStyle(fontWeight: FontWeight.bold)),
                  subtitle: Text("EMAIL: ${userData['email']}\nTIER: 0$currentTier",
                      style: const TextStyle(color: Colors.white38, fontSize: 10)),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _tierBtn(uid, 1, "01"),
                      const SizedBox(width: 4),
                      _tierBtn(uid, 2, "02"),
                      const SizedBox(width: 4),
                      _tierBtn(uid, 3, "03"),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }

  Widget _tierBtn(String uid, int tier, String label) {
    return OutlinedButton(
      style: OutlinedButton.styleFrom(
        minimumSize: const Size(35, 35),
        padding: EdgeInsets.zero,
        side: const BorderSide(color: terminalGreen),
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      ),
      onPressed: () => _updateTier(uid, tier),
      child: Text(label, style: const TextStyle(fontSize: 10, color: terminalGreen)),
    );
  }
}