import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:google_fonts/google_fonts.dart';
import 'feed_view.dart';
import 'music_vault_view.dart';
import 'artifacts_view.dart';
import 'events_view.dart';
import 'community_view.dart';
import 'admin_dashboard_view.dart';
import 'player_service.dart';
import 'full_player_view.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _selectedIndex = 0;

  // COLOR CONSTANTS
  static const Color cyberOrange = Color(0xFFE87D25);
  static const Color dimmedOrange = Color(0xFF4A280B); // Deep "Burnt" Orange for unselected items

  final List<Widget> _pages = [
    const FeedView(),
    const MusicVaultView(),
    const ArtifactsView(),
    const EventsView(),
    const CommunityView(),
  ];

  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser;

    return StreamBuilder<DocumentSnapshot>(
      stream: FirebaseFirestore.instance.collection('users').doc(user?.uid).snapshots(),
      builder: (context, snapshot) {
        bool isAdmin = false;
        if (snapshot.hasData && snapshot.data!.exists) {
          final userData = snapshot.data!.data() as Map<String, dynamic>;
          isAdmin = userData['role'] == 'admin';
        }

        return Scaffold(
          backgroundColor: Colors.black,
          appBar: AppBar(
            backgroundColor: Colors.black,
            title: Image.asset(
              'assets/images/logo.png',
              height: 32,
              color: cyberOrange, // UPDATED
              filterQuality: FilterQuality.high,
            ),
            centerTitle: true,
            leading: const Icon(Icons.lock_outline, color: cyberOrange, size: 16), // UPDATED
            actions: [
              if (isAdmin)
                IconButton(
                  icon: const Icon(Icons.settings_input_component, color: Colors.redAccent, size: 20),
                  onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => AdminDashboardView())),
                ),
              IconButton(
                onPressed: () => FirebaseAuth.instance.signOut(),
                icon: const Icon(Icons.power_settings_new, color: cyberOrange, size: 20), // UPDATED
              )
            ],
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(1.0),
              child: Container(color: cyberOrange.withValues(alpha: 0.2), height: 1.0), // UPDATED
            ),
          ),
          body: Column(
            children: [
              Expanded(child: _pages[_selectedIndex]),

              // MINI PLAYER
              ValueListenableBuilder<Map<String, dynamic>?>(
                valueListenable: PlayerService().currentTrack,
                builder: (context, track, child) {
                  if (track == null) return const SizedBox.shrink();
                  return GestureDetector(
                    onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context) => const FullPlayerView())),
                    child: Container(
                      height: 65,
                      decoration: BoxDecoration(
                        color: const Color(0xFF0A0A0A),
                        border: Border(top: BorderSide(color: cyberOrange.withValues(alpha: 0.5), width: 0.5)),
                      ),
                      padding: const EdgeInsets.symmetric(horizontal: 15),
                      child: Row(
                        children: [
                          Container(
                            width: 45, height: 45,
                            decoration: BoxDecoration(border: Border.all(color: cyberOrange, width: 1)),
                            child: Image.network(track['imageUrl'], fit: BoxFit.cover),
                          ),
                          const SizedBox(width: 15),
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(track['title'].toString().toUpperCase(), style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, letterSpacing: 1, color: cyberOrange)),
                                const Text("STATUS: STREAMING_ACTIVE", style: TextStyle(fontSize: 8, color: cyberOrange)),
                              ],
                            ),
                          ),
                          StreamBuilder<bool>(
                              stream: PlayerService().player.playingStream,
                              builder: (context, snap) {
                                final isPlaying = snap.data ?? false;
                                return IconButton(
                                  icon: Icon(isPlaying ? Icons.pause : Icons.play_arrow, color: cyberOrange),
                                  onPressed: () => PlayerService().toggle(),
                                );
                              }
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
          bottomNavigationBar: Container(
            decoration: BoxDecoration(
              border: Border(top: BorderSide(color: cyberOrange.withValues(alpha: 0.3))),
            ),
            child: BottomNavigationBar(
              currentIndex: _selectedIndex,
              onTap: (index) => setState(() => _selectedIndex = index),
              backgroundColor: Colors.black,
              selectedItemColor: cyberOrange, // UPDATED
              unselectedItemColor: dimmedOrange, // UPDATED: Burnt Orange
              type: BottomNavigationBarType.fixed,
              selectedLabelStyle: GoogleFonts.shareTechMono(fontSize: 9),
              unselectedLabelStyle: GoogleFonts.shareTechMono(fontSize: 9),
              items: const [
                BottomNavigationBarItem(icon: Icon(Icons.radar, size: 20), label: "/BROADCAST/"),
                BottomNavigationBarItem(icon: Icon(Icons.folder_zip_outlined, size: 20), label: "/ARCHIVE/"),
                BottomNavigationBarItem(icon: Icon(Icons.inventory_2_outlined, size: 20), label: "/ARTIFACTS/"),
                BottomNavigationBarItem(icon: Icon(Icons.location_on_outlined, size: 20), label: "/SESSIONS/"),
                BottomNavigationBarItem(icon: Icon(Icons.terminal, size: 20), label: "/COMMS/"),
              ],
            ),
          ),
        );
      },
    );
  }
}