import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:onsolgo/core/constants.dart';

class AchievementsView extends StatelessWidget {
  const AchievementsView({super.key});

  @override
  Widget build(BuildContext context) {
    final String uid = FirebaseAuth.instance.currentUser?.uid ?? "";
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: const Text("CITIZEN ARCHIVE",
            style: TextStyle(letterSpacing: 3, fontSize: 12, fontWeight: FontWeight.bold)),
        centerTitle: true,
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('users').doc(uid).collection('achievements').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: kOnsolGold));
          final unlocked = snapshot.data!.docs.map((d) => d.id).toList();

          return ListView(
            padding: const EdgeInsets.all(20),
            children: [
              _buildCategory("ONBOARDING", "ACCOUNT", unlocked),
              _buildCategory("READING PROGRESSION", "READING", unlocked),
              _buildCategory("COMMUNITY & ENGAGEMENT", "COMMUNITY", unlocked),
              _buildCategory("THE VAULT", "MARKET", unlocked),
              _buildCategory("SUPPORT & INVESTMENT", "INVEST", unlocked),
              _buildCategory("CONSISTENCY", "CONSISTENCY", unlocked),
              _buildCategory("DISCOVERY", "DISCOVERY", unlocked),
              _buildCategory("RARE / HIDDEN", "RARE", unlocked),
            ],
          );
        },
      ),
    );
  }

  Widget _buildCategory(String title, String cat, List<String> unlocked) {
    final items = kAllAchievements.where((a) => a.category == cat).toList();
    if (items.isEmpty) return const SizedBox.shrink();

    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
              padding: const EdgeInsets.symmetric(vertical: 15),
              child: Text(title,
                  style: const TextStyle(color: kOnsolGold, fontWeight: FontWeight.bold, fontSize: 11, letterSpacing: 1.5))
          ),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 2.1,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10
            ),
            itemCount: items.length,
            itemBuilder: (c, i) {
              final ach = items[i];
              bool done = unlocked.contains(ach.id);

              // NO CONST HERE: Colors are calculated at runtime
              return Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                    color: done ? kOnsolGold.withValues(alpha: 0.1) : Colors.grey[900],
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: done ? kOnsolGold : Colors.transparent, width: 0.5)
                ),
                child: Row(
                    children: [
                      Icon(ach.icon, color: done ? kOnsolGold : Colors.grey, size: 22),
                      const SizedBox(width: 10),
                      Expanded(
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(ach.title,
                                    style: TextStyle(fontSize: 9, fontWeight: FontWeight.bold, color: done ? Colors.white : Colors.grey)),
                                Text(ach.desc,
                                    style: const TextStyle(fontSize: 7, color: Colors.white38), maxLines: 2),
                              ]
                          )
                      ),
                    ]
                ),
              );
            },
          ),
        ]
    );
  }
}