// lib/features/admin/tabs/library/library_dashboard_tab.dart

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

// --- CORE ARCHITECTURE ---
import '../../../../core/models/user.dart';
import '../../../../core/services/database_service.dart';
import '../../../../core/networks/api_client.dart';
import '../../../../core/networks/library_api_service.dart';

// --- LIBRARY PANELS & DIALOGS ---
import 'library_overview_panel.dart';
import 'books_directory_panel.dart';
import 'students_directory_panel.dart';
import 'borrowing_records_panel.dart';
import 'other_campuses_panel.dart'; 
import 'all_records_panel.dart'; // 🚀 ADDED NEW PANEL IMPORT
import 'borrowing_entry_dialog.dart';

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

final CacheManager customSidebarCacheManager = CacheManager(
  Config('sidebarImageCache', stalePeriod: const Duration(days: 30), maxNrOfCacheObjects: 200),
);

ImageProvider? getSidebarImageProvider(String? imageString) {
  if (imageString == null || imageString.trim().isEmpty) return null;
  if (imageString.startsWith('http://') || imageString.startsWith('https://')) {
    return CachedNetworkImageProvider(imageString, cacheManager: customSidebarCacheManager);
  } else if (imageString.startsWith('/data') || imageString.startsWith('C:\\') || imageString.startsWith('storage')) {
    final file = File(imageString);
    if (file.existsSync()) return FileImage(file);
  } else {
    try {
      String cleanBase64 = imageString;
      if (cleanBase64.contains(',')) cleanBase64 = cleanBase64.split(',').last;
      cleanBase64 = cleanBase64.replaceAll(RegExp(r'\s+'), '');
      return MemoryImage(base64Decode(cleanBase64));
    } catch (e) {
      debugPrint('Error decoding base64 image: $e');
    }
  }
  return null;
}

class LibHoverClickable extends StatefulWidget {
  final Widget Function(bool isHovered) builder;
  final VoidCallback? onTap;

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

  @override
  State<LibHoverClickable> createState() => _LibHoverClickableState();
}

class _LibHoverClickableState extends State<LibHoverClickable> {
  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),
      ),
    );
  }
}

class LibHoverMenuLink extends StatefulWidget {
  final String title;
  final IconData icon;
  final bool isSelected;
  final VoidCallback onTap;
  final IconData? trailingIcon;

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

  @override
  State<LibHoverMenuLink> createState() => _LibHoverMenuLinkState();
}

class _LibHoverMenuLinkState extends State<LibHoverMenuLink> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    final showHighlight = _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: 150),
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
          decoration: BoxDecoration(
            color: widget.isSelected 
                ? _darkGreen.withOpacity(0.08) 
                : (_isHovered ? Colors.grey.shade50 : Colors.transparent),
            border: Border(
              left: BorderSide(
                color: showHighlight ? _standardGold : Colors.transparent,
                width: 4.0,
              ),
            ),
          ),
          child: Row(
            children: [
              Icon(
                widget.icon,
                color: widget.isSelected ? _darkGreen : Colors.grey.shade500,
                size: 22,
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Text(
                  widget.title,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: widget.isSelected ? FontWeight.bold : FontWeight.w600,
                    color: widget.isSelected ? _darkGreen : Colors.grey.shade700,
                    letterSpacing: 0.5,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              if (widget.trailingIcon != null)
                Icon(
                  widget.trailingIcon,
                  color: widget.isSelected ? _darkGreen : Colors.grey.shade500,
                  size: 20,
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class LibraryDashboardTab extends StatefulWidget {
  final LocalUser? currentUser;

  const LibraryDashboardTab({super.key, this.currentUser});

  @override
  State<LibraryDashboardTab> createState() => _LibraryDashboardTabState();
}

class _LibraryDashboardTabState extends State<LibraryDashboardTab> {
  int _currentViewIndex = 0;
  LocalUser? _resolvedUser;

  bool _showHeader = false;
  bool _isSidebarOpen = false;
  bool _showActivityLog = false;
  bool _viewAllCampuses = false; 

  bool _isOtherCampusesExpanded = false;
  String? _selectedOtherCampus; 

  int _refreshCounter = 0;
  Timer? _autoRefreshTimer;

  List<dynamic> _activityLogs = [];
  bool _isLoadingLogs = false;
  List<dynamic> _dbCampuses = [];

  @override
  void initState() {
    super.initState();
    _initDashboardData();
    // Library panels keep their initial Future in State. Listen for writes and
    // cache replacements so the active panel reloads without app restart.
    ApiClient.dataChanges.addListener(_onLibraryDataChanged);

    _autoRefreshTimer = Timer.periodic(const Duration(seconds: 6), (_) {
      if (_showActivityLog) {
        _fetchActivityLogs(silent: true, refresh: true);
      }
    });
  }

  @override
  void didUpdateWidget(covariant LibraryDashboardTab oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.currentUser != widget.currentUser) {
      setState(() {
        _resolvedUser = widget.currentUser ?? _resolvedUser;
        _selectedOtherCampus = null; 
      });
      _fetchActivityLogs(silent: true, refresh: true);
    }
  }

  @override
  void dispose() {
    ApiClient.dataChanges.removeListener(_onLibraryDataChanged);
    _autoRefreshTimer?.cancel();
    super.dispose();
  }

  void _onLibraryDataChanged() {
    final change = ApiClient.dataChanges.value;
    if (!mounted || change == null) return;
    final libraryEndpoint = Uri.parse('${ApiClient.baseUrl}/api/library.php');
    if (!ApiClient.sameApiFamily(change.url, libraryEndpoint)) return;
    // Cache-sync notifications can be produced by the global panel's own
    // three parallel reads. Do not recreate that panel for those notifications
    // or its initial fetch cycle will keep restarting. Successful writes still
    // recreate it so its new instance performs a forced server read.
    final shouldRecreateForMutation = change.isMutation &&
        _currentViewIndex != 1 &&
        _currentViewIndex != 2 &&
        _currentViewIndex != 3;
    final shouldRecreateForCacheSync = !change.isMutation &&
        _currentViewIndex != 1 &&
        _currentViewIndex != 2 &&
        _currentViewIndex != 3 &&
        _currentViewIndex != 5;
    if (shouldRecreateForMutation || shouldRecreateForCacheSync) {
      setState(() => _refreshCounter++);
    }
    if (_showActivityLog) _fetchActivityLogs(silent: true, refresh: true);
  }

  Future<void> _initDashboardData() async {
    await _fetchCurrentUser();
    await _fetchDatabaseCampuses();
  }

  Future<void> _fetchCurrentUser() async {
    final localUser = await DatabaseService.getLocalUser();
    if (mounted) {
      setState(() {
        _resolvedUser = widget.currentUser ?? localUser;
      });
    }
  }

  Future<void> _fetchDatabaseCampuses() async {
    try {
      final campuses = await ApiClient.getCampuses();
      if (mounted) {
        setState(() => _dbCampuses = campuses);
      }
    } catch (e) {
      debugPrint("Error fetching database campuses: $e");
    }
  }

  String _resolveActiveCampus() {
    final userCampus = _resolvedUser?.campus?.trim() ?? '';
    if (userCampus.isNotEmpty) return userCampus;
    return 'Main Campus';
  }

  String get _effectiveCampus => _selectedOtherCampus ?? _resolveActiveCampus();

  Future<void> _fetchActivityLogs({bool silent = false, bool refresh = false}) async {
    if (!silent) setState(() => _isLoadingLogs = true);
    try {
      final records = await LibraryApiService.getBorrowingRecords(refresh: refresh);
      final activeCampus = _effectiveCampus.toLowerCase(); 

      final campusFiltered = _viewAllCampuses ? records : records.where((rec) {
        final recordCampus = (rec['campus'] ?? rec['campus_name'] ?? '').toString().toLowerCase().trim();
        if (recordCampus.isEmpty) return true;
        return recordCampus.contains(activeCampus) || activeCampus.contains(recordCampus);
      }).toList();

      campusFiltered.sort((a, b) {
        final dateA = DateTime.tryParse((a['borrow_date'] ?? a['created_at'] ?? '').toString()) ?? DateTime.fromMillisecondsSinceEpoch(0);
        final dateB = DateTime.tryParse((b['borrow_date'] ?? b['created_at'] ?? '').toString()) ?? DateTime.fromMillisecondsSinceEpoch(0);
        return dateB.compareTo(dateA);
      });

      if (mounted) {
        setState(() {
          _activityLogs = campusFiltered;
          if (!silent) _isLoadingLogs = false;
        });
      }
    } catch (e) {
      debugPrint("Error loading circulation activity: $e");
      if (mounted && !silent) setState(() => _isLoadingLogs = false);
    }
  }

  void _switchTab(int index, {bool isDashboardOverview = false}) {
    setState(() {
      _currentViewIndex = index;
      _isSidebarOpen = false;
      _showActivityLog = false;
      
      if (isDashboardOverview) {
        _selectedOtherCampus = null; 
      }
    });
  }

  void _toggleSidebar() {
    setState(() {
      _isSidebarOpen = !_isSidebarOpen;
      if (_isSidebarOpen) _showActivityLog = false;
    });
  }

  void _toggleActivityLog() {
    setState(() {
      _showActivityLog = !_showActivityLog;
      if (_showActivityLog) {
        _isSidebarOpen = false;
        _fetchActivityLogs(refresh: true);
      }
    });
  }

  void _triggerDataRefresh() {
    setState(() => _refreshCounter++);
    if (_showActivityLog) {
      _fetchActivityLogs(silent: true, refresh: true);
    }
  }

  Widget _getCurrentTab() {
    final String keySuffix = '${_currentViewIndex}_${_refreshCounter}_$_effectiveCampus';

    switch (_currentViewIndex) {
      case 0:
        return LibraryOverviewPanel(key: ValueKey('overview_$keySuffix'), currentUser: _resolvedUser);
      case 1:
        return BooksDirectoryPanel(key: ValueKey('books_$keySuffix'));
      case 2:
        return StudentsDirectoryPanel(key: ValueKey('students_$keySuffix'));
      case 3:
        return BorrowingRecordsPanel(key: ValueKey('borrowing_$keySuffix'));
      case 4: 
        return OtherCampusesPanel(
          key: ValueKey('other_campus_${_selectedOtherCampus}_$keySuffix'), 
          campusName: _selectedOtherCampus ?? 'Unknown Campus',
          currentUser: _resolvedUser,
        );
      case 5: // 🚀 ADDED ROUTE FOR NEW PANEL
        return AllRecordsPanel(key: ValueKey('all_records_$keySuffix'));
      default:
        return LibraryOverviewPanel(key: ValueKey('overview_$keySuffix'), currentUser: _resolvedUser);
    }
  }

  Widget _buildOtherCampusesDropdown() {
    final myCampus = _resolveActiveCampus().toLowerCase();
    
    final otherCampuses = _dbCampuses
        .map((c) => (c['name'] ?? '').toString()) 
        .where((c) => c.isNotEmpty && !c.toLowerCase().contains(myCampus))
        .toSet() 
        .toList();

    if (otherCampuses.isEmpty) return const SizedBox.shrink();

    return Column(
      children: [
        LibHoverMenuLink(
          title: 'Other Campuses',
          icon: Icons.domain_rounded,
          isSelected: _selectedOtherCampus != null,
          trailingIcon: _isOtherCampusesExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
          onTap: () {
            setState(() {
              _isOtherCampusesExpanded = !_isOtherCampusesExpanded;
            });
          },
        ),
        AnimatedSize(
          duration: const Duration(milliseconds: 300),
          curve: Curves.fastOutSlowIn,
          child: _isOtherCampusesExpanded
            ? Container(
                color: Colors.grey.shade50,
                width: double.infinity,
                child: Column(
                  children: otherCampuses.map((campus) {
                    final isSelected = _selectedOtherCampus == campus && _currentViewIndex == 4;
                    return InkWell(
                      onTap: () {
                        setState(() {
                          _selectedOtherCampus = campus;
                          _currentViewIndex = 4; 
                          if (_showActivityLog) _fetchActivityLogs(refresh: true); 
                          if (MediaQuery.of(context).size.width <= 950) {
                             _isSidebarOpen = false;
                          }
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.only(left: 56, right: 24, top: 14, bottom: 14),
                        decoration: BoxDecoration(
                          color: isSelected ? _darkGreen.withOpacity(0.08) : Colors.transparent,
                          border: Border(left: BorderSide(color: isSelected ? _standardGold : Colors.transparent, width: 4.0))
                        ),
                        child: Row(
                          children: [
                            Icon(Icons.location_on, size: 16, color: isSelected ? _darkGreen : Colors.grey.shade500),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Text(campus, style: TextStyle(fontSize: 13, fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, color: isSelected ? _darkGreen : Colors.grey.shade700)),
                            )
                          ]
                        )
                      )
                    );
                  }).toList(),
                ),
              )
            : const SizedBox(width: double.infinity, height: 0),
        )
      ]
    );
  }

  @override
  Widget build(BuildContext context) {
    final String adminName = _resolvedUser?.fullName ?? 'System Admin';
    final String adminTitle = _resolvedUser?.role ?? 'Librarian';
    final String? adminPic = _resolvedUser?.profilePicture;
    final ImageProvider? imageProvider = getSidebarImageProvider(adminPic);

    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final isDesktop = constraints.maxWidth > 950;
          final isMobile = constraints.maxWidth <= 600;

          return Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AnimatedSize(
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.fastOutSlowIn,
                    alignment: Alignment.topCenter,
                    clipBehavior: Clip.hardEdge,
                    child: _showHeader
                        ? Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border(bottom: BorderSide(color: Colors.grey.shade300, width: 1.0)),
                            ),
                            padding: const EdgeInsets.all(20.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: Row(
                                    children: [
                                      LibHoverClickable(
                                        onTap: _toggleSidebar,
                                        builder: (isHovered) => Container(
                                          padding: const EdgeInsets.all(8.0),
                                          margin: const EdgeInsets.only(right: 16.0),
                                          decoration: BoxDecoration(
                                            color: isHovered ? Colors.grey.shade100 : Colors.transparent,
                                            border: Border.all(color: Colors.grey.shade300),
                                          ),
                                          child: const Icon(Icons.menu_rounded, color: _darkGreen, size: 24.0),
                                        ),
                                      ),
                                      if (!isMobile) const SizedBox(width: 8.0),
                                      if (!isMobile)
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              RichText(
                                                text: TextSpan(
                                                  children: [
                                                    if (isDesktop)
                                                      const TextSpan(
                                                        text: 'UNIVERSITY ',
                                                        style: TextStyle(color: _darkGreen, fontSize: 20.0, fontWeight: FontWeight.w900, letterSpacing: 1.2),
                                                      ),
                                                    const TextSpan(
                                                      text: 'LIBRARY SYSTEM',
                                                      style: TextStyle(color: _standardGold, fontSize: 20.0, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              const SizedBox(height: 6.0),
                                              Container(
                                                padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
                                                decoration: BoxDecoration(
                                                  color: _standardGold.withOpacity(0.1),
                                                  borderRadius: BorderRadius.circular(20.0),
                                                  border: Border.all(color: _standardGold.withOpacity(0.4)),
                                                ),
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    const Icon(Icons.location_on, color: _standardGold, size: 12.0),
                                                    const SizedBox(width: 4.0),
                                                    Text(_effectiveCampus.toUpperCase(), style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.w800, fontSize: 10.0, letterSpacing: 0.5)),
                                                  ],
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                    ],
                                  ),
                                ),
                                Row(
                                  children: [
                                    ElevatedButton.icon(
                                      onPressed: _toggleActivityLog,
                                      icon: Icon(_showActivityLog ? Icons.close : Icons.history_rounded, color: _darkGreen, size: 18.0),
                                      label: Text(
                                        isMobile ? 'LOG' : 'ACTIVITY LOG',
                                        style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.bold, letterSpacing: 0.5),
                                      ),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: _darkGreen.withOpacity(0.1),
                                        foregroundColor: _darkGreen,
                                        elevation: 0,
                                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)),
                                        padding: EdgeInsets.symmetric(horizontal: isMobile ? 12.0 : 20.0, vertical: 16.0),
                                      ),
                                    ),
                                    const SizedBox(width: 12.0),
                                    ElevatedButton.icon(
                                      onPressed: () async {
                                        final result = await showDialog<bool>(
                                          context: context,
                                          builder: (_) => const BorrowingEntryDialog(),
                                        );
                                        if (result == true) _triggerDataRefresh();
                                      },
                                      icon: const Icon(Icons.bookmark_add_rounded, color: Colors.white, size: 18.0),
                                      label: Text(
                                        isMobile ? 'ISSUE' : 'ISSUE BOOK',
                                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                                      ),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: _standardGold,
                                        foregroundColor: Colors.white,
                                        elevation: 0,
                                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)),
                                        padding: EdgeInsets.symmetric(horizontal: isMobile ? 12.0 : 24.0, vertical: 18.0),
                                      ),
                                    ),
                                    const SizedBox(width: 16.0),
                                    _buildSharpCollapseButton(
                                      onTap: () => setState(() => _showHeader = false),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          )
                        : const SizedBox(width: double.infinity, height: 0.0),
                  ),
                  if (!_showHeader) const SizedBox(height: 48.0),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 24.0),
                      child: AnimatedSwitcher(
                        duration: const Duration(milliseconds: 400),
                        switchInCurve: Curves.easeOutQuart,
                        switchOutCurve: Curves.easeInQuart,
                        transitionBuilder: (Widget child, Animation<double> animation) {
                          final slide = Tween<Offset>(begin: const Offset(0.0, 0.05), end: Offset.zero).animate(animation);
                          return FadeTransition(
                            opacity: animation,
                            child: SlideTransition(
                              position: slide,
                              child: child,
                            ),
                          );
                        },
                        child: _getCurrentTab(),
                      ),
                    ),
                  ),
                ],
              ),
              if (!_showHeader)
                Positioned(
                  top: 24.0,
                  left: 24.0,
                  child: _buildFloatingHamburger(),
                ),
              if (!_showHeader)
                Positioned(
                  top: 0.0,
                  left: 0.0,
                  right: 0.0,
                  child: Center(
                    child: _buildChevron(onTap: () => setState(() => _showHeader = true)),
                  ),
                ),
              if (_isSidebarOpen || _showActivityLog)
                Positioned.fill(
                  child: GestureDetector(
                    onTap: () => setState(() {
                      _isSidebarOpen = false;
                      _showActivityLog = false;
                    }),
                    child: Container(color: Colors.black.withOpacity(0.3)),
                  ),
                ),
              AnimatedPositioned(
                duration: const Duration(milliseconds: 350),
                curve: Curves.fastOutSlowIn,
                top: 0.0,
                bottom: 0.0,
                left: _isSidebarOpen ? 0.0 : -320.0,
                child: Container(
                  width: 320.0,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(right: BorderSide(color: Colors.grey.shade300, width: 1.0)),
                    boxShadow: [
                      if (_isSidebarOpen)
                        BoxShadow(color: Colors.black.withOpacity(0.15), blurRadius: 30.0, offset: const Offset(5.0, 0.0)),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: 24.0, right: 24.0, top: 40.0, bottom: 24.0),
                        decoration: const BoxDecoration(
                          color: _darkGreen,
                          border: Border(bottom: BorderSide(color: _standardGold, width: 4.0)),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  'LIBRARY MODULES',
                                  style: TextStyle(color: Colors.white, fontSize: 13.0, fontWeight: FontWeight.bold, letterSpacing: 2.0),
                                ),
                                IconButton(
                                  onPressed: _toggleSidebar,
                                  icon: const Icon(Icons.close_rounded, color: Colors.white),
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                ),
                              ],
                            ),
                            const SizedBox(height: 24.0),
                            Row(
                              children: [
                                CircleAvatar(
                                  radius: 24.0,
                                  backgroundColor: Colors.white24,
                                  backgroundImage: imageProvider,
                                  child: imageProvider == null ? Text(adminName[0].toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0)) : null,
                                ),
                                const SizedBox(width: 16.0),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(adminName, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16.0), maxLines: 1, overflow: TextOverflow.ellipsis),
                                      const SizedBox(height: 4.0),
                                      Text(adminTitle, style: const TextStyle(color: Colors.white70, fontSize: 13.0, fontWeight: FontWeight.w500), maxLines: 1, overflow: TextOverflow.ellipsis),
                                    ],
                                  ),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        child: ListView(
                          padding: const EdgeInsets.symmetric(vertical: 16.0),
                          physics: const BouncingScrollPhysics(),
                          children: [
                            LibHoverMenuLink(
                              title: 'Dashboard Overview', 
                              icon: Icons.dashboard_rounded, 
                              isSelected: _currentViewIndex == 0 && _selectedOtherCampus == null, 
                              onTap: () => _switchTab(0, isDashboardOverview: true) 
                            ),
                            LibHoverMenuLink(title: 'Books Directory', icon: Icons.menu_book_rounded, isSelected: _currentViewIndex == 1, onTap: () => _switchTab(1)),
                            LibHoverMenuLink(title: 'Student Records', icon: Icons.people_alt_rounded, isSelected: _currentViewIndex == 2, onTap: () => _switchTab(2)),
                            LibHoverMenuLink(title: 'Borrowing & Returns', icon: Icons.sync_alt_rounded, isSelected: _currentViewIndex == 3, onTap: () => _switchTab(3)),
                            // 🚀 ADDED THE NEW MODULE LINK HERE
                            LibHoverMenuLink(title: 'All Records (Global)', icon: Icons.format_list_bulleted_rounded, isSelected: _currentViewIndex == 5, onTap: () => _switchTab(5)),
                            
                            const Padding(
                              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                              child: Divider(color: Colors.black12, height: 1),
                            ),
                            
                            _buildOtherCampusesDropdown(),
                          ],
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.all(24.0),
                        decoration: BoxDecoration(border: Border(top: BorderSide(color: Colors.grey.shade200, width: 1.0))),
                        child: Text(
                          'Rockview University\nLibrary Management System',
                          style: TextStyle(color: Colors.grey.shade500, fontSize: 11.0, height: 1.5),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              AnimatedPositioned(
                duration: const Duration(milliseconds: 350),
                curve: Curves.fastOutSlowIn,
                top: 0.0,
                bottom: 0.0,
                right: _showActivityLog ? 0.0 : -(isMobile ? constraints.maxWidth : 380.0),
                child: Container(
                  width: isMobile ? constraints.maxWidth * 0.85 : 380.0,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(left: BorderSide(color: Colors.grey.shade300, width: 1.0)),
                    boxShadow: [
                      if (_showActivityLog)
                        BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 20.0, offset: const Offset(-5.0, 0.0)),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container(
                        padding: const EdgeInsets.fromLTRB(24.0, 40.0, 24.0, 20.0),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade50,
                          border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Row(
                              children: [
                                Icon(Icons.history_rounded, color: _darkGreen, size: 22.0),
                                SizedBox(width: 12.0),
                                Text('Recent Activity', style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.black87)),
                              ],
                            ),
                            IconButton(
                              onPressed: _toggleActivityLog,
                              icon: const Icon(Icons.close_rounded, color: Colors.grey),
                              padding: EdgeInsets.zero,
                              constraints: const BoxConstraints(),
                            )
                          ],
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
                        color: _standardGold.withOpacity(0.1),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Row(
                                children: [
                                  const Icon(Icons.info_outline, size: 14.0, color: _standardGold),
                                  const SizedBox(width: 8.0),
                                  Expanded(
                                    child: Text(
                                      _viewAllCampuses ? "Showing logs for ALL Campuses." : "Logs for $_effectiveCampus.", 
                                      style: const TextStyle(fontSize: 12.0, color: _darkGreen, fontWeight: FontWeight.w600)
                                    )
                                  ),
                                ],
                              ),
                            ),
                            TextButton(
                              onPressed: () {
                                setState(() => _viewAllCampuses = !_viewAllCampuses);
                                _fetchActivityLogs(refresh: true);
                              },
                              style: TextButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0),
                                minimumSize: Size.zero,
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              ),
                              child: Text(
                                _viewAllCampuses ? "View Local" : "View All",
                                style: const TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold, color: _standardGold),
                              ),
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        child: _isLoadingLogs
                            ? const Center(child: CircularProgressIndicator(color: _darkGreen))
                            : _activityLogs.isEmpty
                                ? Center(child: Text("No recent activity for $_effectiveCampus.", style: TextStyle(color: Colors.grey.shade500, fontStyle: FontStyle.italic)))
                                : ListView.separated(
                                    physics: const BouncingScrollPhysics(),
                                    padding: const EdgeInsets.symmetric(vertical: 16.0),
                                    itemCount: _activityLogs.length,
                                    separatorBuilder: (context, index) => Divider(color: Colors.grey.shade100, height: 1.0),
                                    itemBuilder: (context, index) {
                                      final activity = _activityLogs[index];
                                      final bool isReturned = activity['status']?.toString().toUpperCase() == 'RETURNED';

                                      final String bookTitle = activity['book_title']?.toString() ?? '';
                                      final String bookId = activity['book_id']?.toString() ?? '';
                                      final String displayBook = bookTitle.isNotEmpty ? bookTitle : (bookId.isNotEmpty ? 'ID: $bookId' : 'Unknown Book');

                                      final String studentId = activity['student_id']?.toString() ?? 'Unknown ID';

                                      String timeAgo = 'Just now';
                                      final rawDate = activity['borrow_date'] ?? activity['created_at'] ?? activity['due_date'];
                                      if (rawDate != null) {
                                        final parsedDate = DateTime.tryParse(rawDate.toString());
                                        if (parsedDate != null) {
                                          final diff = DateTime.now().difference(parsedDate);
                                          if (diff.inDays > 0) {
                                            timeAgo = '${diff.inDays}d ago';
                                          } else if (diff.inHours > 0) {
                                            timeAgo = '${diff.inHours}h ago';
                                          } else if (diff.inMinutes > 0) {
                                            timeAgo = '${diff.inMinutes}m ago';
                                          }
                                        }
                                      }

                                      return ListTile(
                                        contentPadding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 8.0),
                                        leading: Container(
                                          padding: const EdgeInsets.all(10.0),
                                          decoration: BoxDecoration(
                                            color: isReturned ? Colors.green.shade50 : _standardGold.withOpacity(0.1),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            isReturned ? Icons.assignment_returned_rounded : Icons.outbond_rounded,
                                            color: isReturned ? _darkGreen : _standardGold,
                                            size: 18.0,
                                          ),
                                        ),
                                        title: Text(
                                          isReturned ? 'Book Returned' : 'Book Issued',
                                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0),
                                        ),
                                        subtitle: Padding(
                                          padding: const EdgeInsets.only(top: 4.0),
                                          child: Text('Student ID: $studentId \nBook: $displayBook', style: TextStyle(color: Colors.grey.shade600, fontSize: 12.0, height: 1.4)),
                                        ),
                                        trailing: Text(timeAgo, style: TextStyle(color: Colors.grey.shade400, fontSize: 11.0, fontWeight: FontWeight.w600)),
                                      );
                                    },
                                  ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildFloatingHamburger() {
    return LibHoverClickable(
      onTap: _toggleSidebar,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.zero,
          border: Border.all(color: Colors.grey.shade300, width: 1.0),
          boxShadow: [
            BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 8.0, offset: const Offset(0.0, 2.0)),
          ],
        ),
        child: const Icon(Icons.menu_rounded, color: _darkGreen, size: 24.0),
      ),
    );
  }

  Widget _buildSharpCollapseButton({required VoidCallback onTap}) {
    return LibHoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.transparent,
          borderRadius: BorderRadius.zero,
          border: Border.all(color: _standardGold, width: 2.0),
        ),
        child: Icon(
          Icons.keyboard_arrow_up_rounded,
          color: isHovered ? Colors.white : _standardGold,
          size: 20.0,
        ),
      ),
    );
  }

  Widget _buildChevron({required VoidCallback onTap}) {
    return LibHoverClickable(
      onTap: onTap,
      builder: (isHovered) => AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOut,
        margin: const EdgeInsets.only(top: 0.0),
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 8.0),
        decoration: BoxDecoration(
          color: isHovered ? _standardGold : Colors.white,
          borderRadius: const BorderRadius.vertical(bottom: Radius.circular(0.0)),
          border: Border.all(color: _standardGold, width: 2.0),
          boxShadow: [
            BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 8.0, offset: const Offset(0.0, 4.0)),
          ],
        ),
        child: Icon(
          Icons.keyboard_arrow_down_rounded,
          color: isHovered ? Colors.white : _darkGreen,
          size: 24.0,
        ),
      ),
    );
  }
}
