// lib/features/admin/tabs/kpi/admin_kpi_dashboard_tab.dart

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

// Import all the newly created modules
import 'executive_overview_panel.dart';
import 'department_drilldown_panel.dart';
import 'kpi_trend_chart.dart';
import 'kpi_data_entry_dialog.dart';

// Import the newly integrated Library Dashboard
import '../library/library_dashboard_tab.dart';

// Standard App Colors
const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);

// =====================================================================
// HOVER WRAPPER WIDGETS
// =====================================================================
class HoverClickable extends StatefulWidget {
  final Widget Function(bool isHovered) builder;
  final VoidCallback? onTap;

  const HoverClickable({super.key, required this.builder, this.onTap});

  @override
  State<HoverClickable> createState() => _HoverClickableState();
}

class _HoverClickableState extends State<HoverClickable> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: widget.onTap != null ? SystemMouseCursors.click : SystemMouseCursors.basic,
      child: GestureDetector(
        onTap: widget.onTap,
        child: widget.builder(_isHovered),
      ),
    );
  }
}

// Custom widget for sidebar links with underline hover effect
class HoverMenuLink extends StatefulWidget {
  final String title;
  final IconData icon;
  final bool isSelected;
  final VoidCallback onTap;

  const HoverMenuLink({
    super.key,
    required this.title,
    required this.icon,
    required this.isSelected,
    required this.onTap,
  });

  @override
  State<HoverMenuLink> createState() => _HoverMenuLinkState();
}

class _HoverMenuLinkState extends State<HoverMenuLink> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    final showUnderline = _isHovered || widget.isSelected;

    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
          decoration: BoxDecoration(
            color: widget.isSelected ? Colors.grey.shade100 : Colors.transparent,
            border: Border(
              bottom: BorderSide(
                color: showUnderline ? _standardGold : Colors.transparent,
                width: 3,
              ),
            ),
          ),
          child: Row(
            children: [
              Icon(
                widget.icon,
                color: widget.isSelected ? _darkGreen : Colors.grey.shade600,
                size: 22,
              ),
              const SizedBox(width: 16),
              Text(
                widget.title,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: widget.isSelected ? FontWeight.bold : FontWeight.w600,
                  color: widget.isSelected ? _darkGreen : Colors.grey.shade800,
                  letterSpacing: 0.5,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

  @override
  State<AdminKpiDashboardTab> createState() => _AdminKpiDashboardTabState();
}

class _AdminKpiDashboardTabState extends State<AdminKpiDashboardTab> {
  // Navigation State
  int _currentViewIndex = 0;
  
  // UI States
  bool _showHeader = false;
  bool _isSidebarOpen = false;

  void _switchTab(int index) {
    setState(() {
      _currentViewIndex = index;
      _isSidebarOpen = false; // Auto-close sidebar on selection
    });
  }

  void _toggleSidebar() {
    setState(() {
      _isSidebarOpen = !_isSidebarOpen;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final isDesktop = constraints.maxWidth > 800;

          return Stack(
            children: [
              // --- MAIN CONTENT LAYER ---
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // --- COLLAPSIBLE HEADER & ACTION AREA ---
                  AnimatedSize(
                    duration: const Duration(milliseconds: 600),
                    curve: Curves.fastOutSlowIn,
                    alignment: Alignment.topCenter,
                    child: SizedBox(
                      height: _showHeader ? null : 0.0,
                      width: double.infinity,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(bottom: BorderSide(color: Colors.grey.shade200, width: 1)),
                        ),
                        padding: const EdgeInsets.all(24.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            // Left Section: Hamburger Menu + Title
                            Expanded(
                              child: Row(
                                children: [
                                  // Hamburger Icon
                                   HoverClickable(
                                     onTap: _toggleSidebar,
                                     builder: (isHovered) => Container(
                                       padding: const EdgeInsets.all(8),
                                       margin: const EdgeInsets.only(right: 16),
                                       decoration: BoxDecoration(
                                         color: isHovered ? Colors.grey.shade100 : Colors.transparent,
                                         border: Border.all(color: Colors.grey.shade300),
                                         borderRadius: BorderRadius.zero, // Sharp edges
                                       ),
                                       child: const Icon(Icons.menu_rounded, color: _darkGreen, size: 28),
                                     ),
                                   ),
                                  const SizedBox(width: 16),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        RichText(
                                          text: TextSpan(
                                            children: [
                                              TextSpan(
                                                text: 'UNIVERSITY ', 
                                                style: TextStyle(
                                                  color: _darkGreen, 
                                                  fontSize: isDesktop ? 24 : 18, 
                                                  fontWeight: FontWeight.w900, 
                                                  letterSpacing: 1.2
                                                )
                                              ),
                                              TextSpan(
                                                text: 'KPI DASHBOARD', 
                                                style: TextStyle(
                                                  color: _standardGold, 
                                                  fontSize: isDesktop ? 24 : 18, 
                                                  fontWeight: FontWeight.w400, 
                                                  letterSpacing: 1.2
                                                )
                                              ),
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 4),
                                        Text(
                                          'Executive Performance Overview & Departmental Tracking',
                                          style: TextStyle(
                                            fontSize: isDesktop ? 14 : 12,
                                            color: Colors.grey.shade700,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            
                            // Right Section: Action Button + Collapse Icon
                            if (isDesktop)
                              ElevatedButton.icon(
                                onPressed: () => _switchTab(3), // Data Entry Tab
                                icon: const Icon(Icons.add_chart_rounded, color: Colors.white),
                                label: const Text(
                                  'INPUT MONTHLY DATA',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    letterSpacing: 1.0,
                                  ),
                                ),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: _standardGold,
                                  foregroundColor: Colors.white,
                                  elevation: 0,
                                  shape: const RoundedRectangleBorder(
                                    borderRadius: BorderRadius.zero, 
                                  ),
                                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
                                ),
                              ),
                              
                            const SizedBox(width: 16),
                            
                            _buildCircularCollapseButton(
                              onTap: () => setState(() => _showHeader = false)
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  // Top spacing if header is hidden
                  if (!_showHeader) const SizedBox(height: 48), 
                  
                  // --- DYNAMIC CONTENT AREA ---
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 24.0),
                      child: IndexedStack(
                        index: _currentViewIndex,
                        children: [
                          const ExecutiveOverviewPanel(),
                          const DepartmentDrilldownPanel(),
                          _buildFullTrendAnalysisTab(), 
                          const SingleChildScrollView(
                            child: Padding(
                              padding: EdgeInsets.symmetric(vertical: 24.0),
                              child: KpiDataEntryDialog(),
                            ),
                          ),
                          const LibraryDashboardTab(), // Integrated Library Dashboard
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              
              // --- FLOATING MENU ICON (Far Left) ---
              if (!_showHeader)
                Positioned(
                  top: 24, 
                  left: 24,
                  child: _buildFloatingHamburger(),
                ),

              // --- FLOATING REVEAL CHEVRON (Center) ---
              if (!_showHeader)
                Positioned(
                  top: 0,
                  left: 0, 
                  right: 0,
                  child: Center(
                    child: _buildChevron(onTap: () => setState(() => _showHeader = true)),
                  ),
                ),

              // --- SIDEBAR OVERLAY BACKGROUND ---
              if (_isSidebarOpen)
                Positioned.fill(
                  child: GestureDetector(
                    onTap: _toggleSidebar, // Close sidebar when tapping outside
                    child: Container(
                      color: Colors.black.withOpacity(0.3),
                    ),
                  ),
                ),

              // --- SLIDING SIDEBAR MENU ---
              AnimatedPositioned(
                duration: const Duration(milliseconds: 350),
                curve: Curves.fastOutSlowIn,
                top: 0,
                bottom: 0,
                left: _isSidebarOpen ? 0 : -350, // Slide in from left
                child: Container(
                  width: 350,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(right: BorderSide(color: Colors.grey.shade300, width: 1)),
                    boxShadow: [
                      if (_isSidebarOpen)
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 20,
                          offset: const Offset(5, 0),
                        ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // Sidebar Header
                      Container(
                        padding: const EdgeInsets.all(24),
                        decoration: const BoxDecoration(
                          color: _darkGreen,
                          border: Border(bottom: BorderSide(color: _standardGold, width: 4)),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              'KPI MODULES',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                letterSpacing: 1.5,
                              ),
                            ),
                            IconButton(
                              onPressed: _toggleSidebar,
                              icon: const Icon(Icons.close_rounded, color: Colors.white),
                              splashRadius: 20,
                            ),
                          ],
                        ),
                      ),
                      // Sidebar Links
                      Expanded(
                        child: ListView(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          children: [
                            HoverMenuLink(
                              title: 'Executive Overview',
                              icon: Icons.dashboard_rounded,
                              isSelected: _currentViewIndex == 0,
                              onTap: () => _switchTab(0),
                            ),
                            HoverMenuLink(
                              title: 'Department Drill-Down',
                              icon: Icons.account_tree_rounded,
                              isSelected: _currentViewIndex == 1,
                              onTap: () => _switchTab(1),
                            ),
                            HoverMenuLink(
                              title: 'Trend Analysis',
                              icon: Icons.show_chart_rounded,
                              isSelected: _currentViewIndex == 2,
                              onTap: () => _switchTab(2),
                            ),
                            HoverMenuLink(
                              title: 'Data Entry',
                              icon: Icons.edit_document,
                              isSelected: _currentViewIndex == 3,
                              onTap: () => _switchTab(3),
                            ),
                           // HoverMenuLink(
                           //   title: 'Library Management',
                           //   icon: Icons.local_library_rounded,
                           //   isSelected: _currentViewIndex == 4,
                           //   onTap: () => _switchTab(4),
                           // ),
                          ],
                        ),
                      ),
                      // Optional Sidebar Footer
                      Padding(
                        padding: const EdgeInsets.all(24.0),
                        child: Text(
                          'Rockview University\n KPI Dashboard',
                          style: TextStyle(color: Colors.grey.shade500, fontSize: 11),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // --- FLOATING HAMBURGER (Used when header is collapsed) ---
  Widget _buildFloatingHamburger() {
    return HoverClickable(
      onTap: _toggleSidebar,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
          border: Border.all(color: Colors.grey.shade300, width: 1),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.menu_rounded, color: _darkGreen, size: 24),
      ),
    );
  }

  // --- CIRCULAR COLLAPSE BUTTON (INSIDE HEADER) ---
  Widget _buildCircularCollapseButton({required VoidCallback onTap}) {
    return HoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.transparent,
          shape: BoxShape.circle,
          border: Border.all(color: _standardGold, width: 2),
          boxShadow: isHovered ? [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 4,
              offset: const Offset(0, 2),
            )
          ] : [],
        ),
        child: Icon(
          Icons.keyboard_arrow_up_rounded,
          color: isHovered ? Colors.white : _standardGold,
          size: 20
        ),
      ),
    );
  }

  // --- FLOATING CIRCULAR CHEVRON ---
  Widget _buildChevron({required VoidCallback onTap}) {
    return HoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOut,
        margin: const EdgeInsets.only(top: 16),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.white,
          shape: BoxShape.circle,
          border: Border.all(color: _standardGold, width: 3),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Icon(
          Icons.keyboard_arrow_down_rounded,
          color: isHovered ? Colors.white : _darkGreen,
          size: 28
        ),
      ),
    );
  }

  // --- DEDICATED TREND ANALYSIS TAB UI ---
  Widget _buildFullTrendAnalysisTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 8.0),
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.zero,
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
              ),
              child: const Text(
                'COMPREHENSIVE TREND ANALYSIS (YTD)',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1.0,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(32.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'University Performance Over Time',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: _darkGreen,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Comparing Actual Performance against Institutional Targets',
                    style: TextStyle(color: Colors.grey.shade600),
                  ),
                  const SizedBox(height: 32),
                  SizedBox(
                    height: 500,
                    child: KpiTrendChart(
                      maxY: 100,
                      mainLineColor: _darkGreen,
                      secondaryLineColor: _standardGold,
                      mainLineData: const [
                        FlSpot(0, 42), FlSpot(1, 44), FlSpot(2, 45), FlSpot(3, 45),
                      ],
                      secondaryLineData: const [
                        FlSpot(0, 50), FlSpot(1, 55), FlSpot(2, 60), FlSpot(3, 65),
                        FlSpot(4, 70), FlSpot(5, 75), FlSpot(6, 80), FlSpot(7, 85),
                        FlSpot(8, 90), FlSpot(9, 95), FlSpot(10, 100), FlSpot(11, 100),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}