import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:onsolgo/core/constants.dart';
import 'package:onsolgo/core/streak_manager.dart';
import 'package:onsolgo/screens/library/library_grid.dart';
import 'package:onsolgo/screens/library/trending_list.dart';
import 'package:onsolgo/screens/library/coming_soon.dart';
import 'package:onsolgo/screens/market/market_hub.dart';
import 'package:onsolgo/screens/social/social_feed.dart';
import 'package:onsolgo/screens/profile/profile_view.dart';

class NavigationHub extends StatefulWidget {
  const NavigationHub({super.key});
  @override
  State<NavigationHub> createState() => _NavigationHubState();
}

class _NavigationHubState extends State<NavigationHub> {
  int _currentIndex = 0;

  // REMOVED 'const' from the list to avoid the Constant Expression error
  final List<Widget> _tabs = [
    const LibraryGrid(),
    const TrendingList(),
    const ComingSoon(),
    const MarketHub(),
    const SocialFeed(), // Ensure this only exists in social_feed.dart
  ];

  @override
  void initState() {
    super.initState();
    final String uid = FirebaseAuth.instance.currentUser?.uid ?? "";
    if (uid.isNotEmpty) StreakManager.updateStreak(uid);
  }

  @override
  Widget build(BuildContext context) {
    final String uid = FirebaseAuth.instance.currentUser?.uid ?? "";

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          IndexedStack(index: _currentIndex, children: _tabs),
          Positioned(
            top: MediaQuery.of(context).padding.top + 10,
            right: 20,
            child: SizedBox(
              width: 45, height: 45,
              child: StreamBuilder<DocumentSnapshot>(
                stream: FirebaseFirestore.instance.collection('users').doc(uid).snapshots(),
                builder: (context, snapshot) {
                  int rank = 1; String? pfp;
                  if (snapshot.hasData && snapshot.data!.exists) {
                    var data = snapshot.data!.data() as Map<String, dynamic>;
                    rank = safeInt(data['rankLevel']);
                    pfp = data.containsKey('pfpUrl') ? data['pfpUrl'] : null;
                  }
                  return IconButton(
                    padding: EdgeInsets.zero,
                    // REMOVED 'const' here to fix the build error
                    onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (c) => ProfileView())),
                    icon: Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: getRankColor(rank), width: 1.5),
                        boxShadow: [BoxShadow(color: getRankColor(rank).withValues(alpha: 0.3), blurRadius: 10)],
                      ),
                      child: CircleAvatar(
                        radius: 18,
                        backgroundColor: Colors.black,
                        child: (pfp != null && pfp.isNotEmpty)
                            ? ClipOval(
                                child: CachedNetworkImage(
                                  imageUrl: pfp,
                                  width: 36,
                                  height: 36,
                                  fit: BoxFit.cover,
                                  errorWidget: (context, url, error) => const Icon(Icons.person, size: 20, color: Colors.white),
                                ),
                              )
                            : const Icon(Icons.person, size: 20, color: Colors.white),
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) => setState(() => _currentIndex = index),
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.black,
        selectedItemColor: kOnsolGold,
        unselectedItemColor: Colors.grey,
        selectedFontSize: 10,
        unselectedFontSize: 10,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.grid_view_rounded), label: 'Library'),
          BottomNavigationBarItem(icon: Icon(Icons.local_fire_department), label: 'Hot'),
          BottomNavigationBarItem(icon: Icon(Icons.auto_awesome), label: 'Upcoming'),
          BottomNavigationBarItem(icon: Icon(Icons.token), label: 'Vault'),
          BottomNavigationBarItem(icon: Icon(Icons.forum_rounded), label: 'Social'),
        ],
      ),
    );
  }
}