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

import 'package:flutter/material.dart';
import 'book_entry_dialog.dart';
import 'borrow_entry_dialog.dart';
import 'book_view_dialog.dart';
import '../../../../core/networks/library_api_service.dart'; 
import '../../../../core/services/database_service.dart';
import '../../../../core/models/user.dart';

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

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

  @override
  State<BooksDirectoryPanel> createState() => _BooksDirectoryPanelState();
}

class _BooksDirectoryPanelState extends State<BooksDirectoryPanel> {
  late Future<List<dynamic>> _booksFuture;
  
  // State variables for search filtering
  List<dynamic> _allBooks = [];
  List<dynamic> _filteredBooks = [];
  final TextEditingController _searchController = TextEditingController();

  // Statistics State
  int _totalTitles = 0;
  int _totalCopies = 0;
  int _totalAvailable = 0;
  int _totalIssued = 0;

  // Scroll Controllers required for nested scrollbars
  final ScrollController _verticalScrollController = ScrollController();
  final ScrollController _horizontalScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _booksFuture = _fetchBooks();
    _searchController.addListener(_onSearchChanged);
  }

  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    _verticalScrollController.dispose();
    _horizontalScrollController.dispose();
    super.dispose();
  }

  Future<List<dynamic>> _fetchBooks() async {
    try {
      // 🚀 Concurrently fetch current user, Books, and live Circulation Records
      final responses = await Future.wait([
        DatabaseService.getLocalUser(),
        LibraryApiService.getBooks(),
        LibraryApiService.getBorrowingRecords(),
      ]);
      
      final LocalUser? currentUser = responses[0] as LocalUser?;
      final rawBooks = responses[1] as List<dynamic>;
      final rawRecords = responses[2] as List<dynamic>;

      // 🚀 1. Determine the logged-in admin's absolute campus
      final adminCampus = (currentUser?.campus ?? 'Main Campus').toLowerCase().trim();

      // 🚀 2. Strictly filter the raw books list to match the admin's campus
      final campusBooks = rawBooks.where((book) {
        final c = (book['campus'] ?? book['campus_name'] ?? '').toString().toLowerCase().trim();
        if (c.isEmpty) return false;
        return c == adminCampus || c.contains(adminCampus) || adminCampus.contains(c);
      }).toList();

      // Map active borrowings and borrower IDs by book ID
      final Map<String, int> activeBorrowsMap = {};
      final Map<String, List<String>> borrowersListMap = {};

      for (var record in rawRecords) {
        final status = record['status']?.toString().toUpperCase() ?? '';
        if (status == 'BORROWED' || status == 'ISSUED') {
          final bookId = record['book_id']?.toString() ?? '';
          final studentId = record['student_id']?.toString() ?? 'Unknown Student';
          
          if (bookId.isNotEmpty) {
            activeBorrowsMap[bookId] = (activeBorrowsMap[bookId] ?? 0) + 1;
            borrowersListMap.putIfAbsent(bookId, () => []).add(studentId);
          }
        }
      }
      
      int tTitles = campusBooks.length;
      int tCopies = 0;
      int tAvail = 0;
      int tIssued = 0;

      // Inject the calculated borrows back into the strictly filtered book objects
      final books = campusBooks.map((b) {
        final mutableBook = Map<String, dynamic>.from(b);
        final bId = mutableBook['id']?.toString() ?? '';
        
        final issued = activeBorrowsMap[bId] ?? 0;
        // Backend 'copies' field actually represents the Available inventory
        final available = int.tryParse(mutableBook['copies']?.toString() ?? '0') ?? 0;
        final total = available + issued; // Total never reduces

        mutableBook['issued_copies'] = issued;
        mutableBook['total_copies'] = total;
        mutableBook['active_borrowers_list'] = borrowersListMap[bId] ?? [];

        tCopies += total;
        tAvail += available;
        tIssued += issued;

        return mutableBook;
      }).toList();

      setState(() {
        _allBooks = books;
        _totalTitles = tTitles;
        _totalCopies = tCopies;
        _totalAvailable = tAvail;
        _totalIssued = tIssued;
        
        _filterBooks(_searchController.text); 
      });
      
      return books;
    } catch (e) {
      throw Exception('Failed to load books: $e');
    }
  }

  void _triggerRefresh() {
    setState(() {
      _booksFuture = _fetchBooks();
    });
  }

  void _onSearchChanged() {
    _filterBooks(_searchController.text);
  }

  void _filterBooks(String query) {
    if (query.isEmpty) {
      setState(() {
        _filteredBooks = List.from(_allBooks);
      });
    } else {
      final lowercaseQuery = query.toLowerCase();
      setState(() {
        _filteredBooks = _allBooks.where((book) {
          final id = book['id']?.toString().toLowerCase() ?? '';
          final title = book['title']?.toString().toLowerCase() ?? '';
          return id.contains(lowercaseQuery) || title.contains(lowercaseQuery);
        }).toList();
      });
    }
  }

  Widget _buildStatBadge(String label, String value, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: color.withOpacity(0.08),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '$label: ',
            style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: Colors.grey.shade700),
          ),
          Text(
            value,
            style: TextStyle(fontSize: 12, fontWeight: FontWeight.w900, color: color),
          ),
        ],
      ),
    );
  }

  Future<void> _showWithLoader(BuildContext context, VoidCallback showDialogAction) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(
        child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(_standardGold)),
      ),
    );
    await Future.delayed(const Duration(milliseconds: 500));
    if (context.mounted) {
      Navigator.of(context).pop(); 
      showDialogAction(); 
    }
  }

  void _showInventoryDetailsDialog(BuildContext context, String title, int total, int available, int issued) {
    showDialog(
      context: context,
      builder: (_) => Dialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor: Colors.white,
        child: Container(
          width: 350,
          decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300, width: 1)),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                decoration: const BoxDecoration(
                  color: _darkGreen,
                  border: Border(bottom: BorderSide(color: _standardGold, width: 4)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      'INVENTORY DETAILS',
                      style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 1.2),
                    ),
                    IconButton(
                      onPressed: () => Navigator.of(context).pop(),
                      icon: const Icon(Icons.close_rounded, color: Colors.white),
                      splashRadius: 20,
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(32.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title, 
                      style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black87, height: 1.4),
                    ),
                    const SizedBox(height: 24),
                    _buildInventoryRow('Total Copies', total.toString(), Icons.library_books_rounded, Colors.blue.shade700),
                    const Divider(height: 32),
                    _buildInventoryRow('Available', available.toString(), Icons.check_circle_outline_rounded, _darkGreen),
                    const Divider(height: 32),
                    _buildInventoryRow('Issued Out', issued.toString(), Icons.outbond_rounded, _standardGold),
                  ],
                )
              )
            ]
          )
        )
      )
    );
  }

  Widget _buildInventoryRow(String label, String value, IconData icon, Color color) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(color: color.withOpacity(0.1), shape: BoxShape.circle),
              child: Icon(icon, color: color, size: 20),
            ),
            const SizedBox(width: 16),
            Text(label.toUpperCase(), style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey.shade600, fontSize: 12, letterSpacing: 0.5)),
          ],
        ),
        Text(value, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: color)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final isDesktop = MediaQuery.of(context).size.width > 1050;

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          if (isDesktop)
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'BOOKS DIRECTORY',
                        style: TextStyle(
                          fontSize: 18, 
                          fontWeight: FontWeight.w900, 
                          color: Colors.grey.shade800, 
                          letterSpacing: 1.5
                        ),
                      ),
                      const SizedBox(height: 12),
                      if (_allBooks.isNotEmpty)
                        Wrap(
                          spacing: 8.0,
                          runSpacing: 8.0,
                          children: [
                            _buildStatBadge('TOTAL TITLES', '$_totalTitles', Colors.blue.shade700),
                            _buildStatBadge('TOTAL COPIES', '$_totalCopies', Colors.purple.shade700),
                            _buildStatBadge('AVAILABLE', '$_totalAvailable', _darkGreen),
                            _buildStatBadge('ISSUED', '$_totalIssued', _standardGold),
                          ],
                        ),
                    ],
                  ),
                ),
                const SizedBox(width: 24),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 300,
                      child: TextField(
                        controller: _searchController,
                        decoration: InputDecoration(
                          hintText: 'Search by Title or ID...',
                          prefixIcon: const Icon(Icons.search, color: Colors.grey),
                          filled: true,
                          fillColor: Colors.white,
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                          border: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _darkGreen, width: 2)),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    ElevatedButton.icon(
                      onPressed: () async {
                        final result = await showDialog<bool>(
                          context: context,
                          builder: (_) => const BookEntryDialog(bookToEdit: null),
                        );
                        if (result == true) {
                          _triggerRefresh();
                        }
                      },
                      icon: const Icon(Icons.library_add_rounded, color: Colors.white),
                      label: const Text(
                        'ADD NEW BOOK',
                        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: 22),
                      ),
                    ),
                  ],
                ),
              ],
            )
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'BOOKS DIRECTORY',
                  style: TextStyle(
                    fontSize: 18, 
                    fontWeight: FontWeight.w900, 
                    color: Colors.grey.shade800, 
                    letterSpacing: 1.5
                  ),
                ),
                const SizedBox(height: 12),
                if (_allBooks.isNotEmpty)
                  Wrap(
                    spacing: 8.0,
                    runSpacing: 8.0,
                    children: [
                      _buildStatBadge('TOTAL TITLES', '$_totalTitles', Colors.blue.shade700),
                      _buildStatBadge('TOTAL COPIES', '$_totalCopies', Colors.purple.shade700),
                      _buildStatBadge('AVAILABLE', '$_totalAvailable', _darkGreen),
                      _buildStatBadge('ISSUED', '$_totalIssued', _standardGold),
                    ],
                  ),
                const SizedBox(height: 24),
                Wrap(
                  spacing: 16.0,
                  runSpacing: 16.0,
                  children: [
                    SizedBox(
                      width: 320,
                      child: TextField(
                        controller: _searchController,
                        decoration: InputDecoration(
                          hintText: 'Search by Title or ID...',
                          prefixIcon: const Icon(Icons.search, color: Colors.grey),
                          filled: true,
                          fillColor: Colors.white,
                          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                          border: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
                          focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _darkGreen, width: 2)),
                        ),
                      ),
                    ),
                    ElevatedButton.icon(
                      onPressed: () async {
                        final result = await showDialog<bool>(
                          context: context,
                          builder: (_) => const BookEntryDialog(bookToEdit: null),
                        );
                        if (result == true) {
                          _triggerRefresh();
                        }
                      },
                      icon: const Icon(Icons.library_add_rounded, color: Colors.white),
                      label: const Text(
                        'ADD NEW BOOK',
                        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: 22),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            
          const SizedBox(height: 24),

          Expanded(
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.grey.shade300, width: 1.5), 
              ),
              child: FutureBuilder<List<dynamic>>(
                future: _booksFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting && _allBooks.isEmpty) {
                    return const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(_darkGreen),
                      ),
                    );
                  }

                  if (snapshot.hasError) {
                    return Center(
                      child: Text(
                        'Error loading books: ${snapshot.error}',
                        style: const TextStyle(color: Colors.redAccent, fontWeight: FontWeight.bold),
                      ),
                    );
                  }

                  if (_filteredBooks.isEmpty) {
                    return Center(
                      child: Text(
                        _searchController.text.isEmpty 
                            ? 'No books found for your campus. Add a new book to the inventory to get started.'
                            : 'No books match your search.',
                        style: const TextStyle(color: Colors.grey, fontStyle: FontStyle.italic),
                      ),
                    );
                  }

                  return LayoutBuilder(
                    builder: (context, constraints) {
                      return Theme(
                        data: Theme.of(context).copyWith(
                          scrollbarTheme: ScrollbarThemeData(
                            thumbColor: WidgetStateProperty.all(_darkGreen.withOpacity(0.6)),
                            trackColor: WidgetStateProperty.all(Colors.grey.shade100),
                            trackBorderColor: WidgetStateProperty.all(Colors.grey.shade300),
                            thickness: WidgetStateProperty.all(12.0),
                            radius: const Radius.circular(0), 
                          ),
                        ),
                        child: Scrollbar(
                          controller: _verticalScrollController,
                          thumbVisibility: true,
                          trackVisibility: true,
                          child: SingleChildScrollView(
                            controller: _verticalScrollController,
                            scrollDirection: Axis.vertical,
                            child: Scrollbar(
                              controller: _horizontalScrollController,
                              thumbVisibility: true,
                              trackVisibility: true,
                              child: SingleChildScrollView(
                                controller: _horizontalScrollController,
                                scrollDirection: Axis.horizontal,
                                child: ConstrainedBox(
                                  constraints: BoxConstraints(minWidth: constraints.maxWidth),
                                  child: DataTable(
                                    columnSpacing: 40.0, 
                                    horizontalMargin: 32.0,
                                    border: TableBorder(
                                      horizontalInside: BorderSide(color: Colors.grey.shade300, width: 1),
                                      verticalInside: BorderSide(color: Colors.grey.shade200, width: 1),
                                    ),
                                    headingRowColor: WidgetStateProperty.resolveWith((states) => _darkGreen),
                                    headingTextStyle: const TextStyle(
                                      color: Colors.white, 
                                      fontWeight: FontWeight.bold,
                                      letterSpacing: 0.5,
                                    ),
                                    dataRowMinHeight: 75, 
                                    dataRowMaxHeight: 75,
                                    dividerThickness: 1,
                                    columns: const [
                                      DataColumn(label: Text('BOOK ID')),
                                      DataColumn(label: Text('TITLE')),
                                      DataColumn(label: Text('INVENTORY')), 
                                      DataColumn(label: Text('STATUS')),
                                      DataColumn(label: Text('ACTIONS')),
                                    ],
                                    rows: _filteredBooks.map((book) {
                                      final bookId = book['id']?.toString() ?? 'N/A';
                                      final title = book['title']?.toString() ?? 'Unknown Title';
                                      
                                      // 🚀 Relying on our properly calculated values
                                      final availableCopies = int.tryParse(book['copies']?.toString() ?? '0') ?? 0;
                                      final issuedCopies = int.tryParse(book['issued_copies']?.toString() ?? '0') ?? 0;
                                      final totalCopies = int.tryParse(book['total_copies']?.toString() ?? '0') ?? 0;
                                      
                                      final isAvailable = availableCopies > 0;
                                      final status = isAvailable ? 'Available' : 'Assigned';

                                      final activeBorrowersList = book['active_borrowers_list'] as List<String>? ?? [];
                                      String borrowersText = activeBorrowersList.isEmpty 
                                          ? 'No active borrowers' 
                                          : activeBorrowersList.map((id) => '- $id').join('\n');

                                      return DataRow(
                                        cells: [
                                          DataCell(Text(bookId, style: const TextStyle(fontWeight: FontWeight.w700))),
                                          DataCell(Text(title, style: const TextStyle(fontWeight: FontWeight.w500))),
                                          DataCell(
                                            TextButton.icon(
                                              onPressed: () => _showWithLoader(
                                                context, 
                                                () => _showInventoryDetailsDialog(context, title, totalCopies, availableCopies, issuedCopies)
                                              ),
                                              icon: const Icon(Icons.analytics_outlined, size: 18),
                                              label: const Text('VIEW', style: TextStyle(fontWeight: FontWeight.bold)),
                                              style: TextButton.styleFrom(
                                                foregroundColor: Colors.blue.shade700,
                                                shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                              ),
                                            ),
                                          ),
                                          DataCell(
                                            Tooltip(
                                              message: !isAvailable ? 'Assigned To:\n$borrowersText' : 'Book is available in inventory',
                                              padding: const EdgeInsets.all(12),
                                              textStyle: const TextStyle(color: Colors.white, fontSize: 13, height: 1.4),
                                              decoration: BoxDecoration(
                                                color: Colors.black87,
                                                borderRadius: BorderRadius.circular(4),
                                              ),
                                              waitDuration: const Duration(milliseconds: 300),
                                              child: Container(
                                                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                                decoration: BoxDecoration(
                                                  color: isAvailable ? Colors.green.shade50 : Colors.red.shade50,
                                                  border: Border.all(color: isAvailable ? Colors.green : Colors.red),
                                                ),
                                                child: Text(
                                                  status,
                                                  style: TextStyle(
                                                    color: isAvailable ? Colors.green.shade700 : Colors.red.shade700,
                                                    fontWeight: FontWeight.bold,
                                                    fontSize: 12,
                                                    letterSpacing: 0.5,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                          DataCell(
                                            Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                TextButton.icon(
                                                  onPressed: () => _showWithLoader(context, () {
                                                    showDialog(
                                                      context: context,
                                                      builder: (_) => BookViewDialog(book: book),
                                                    );
                                                  }),
                                                  icon: const Icon(Icons.info_outline_rounded, size: 18),
                                                  style: TextButton.styleFrom(
                                                    foregroundColor: _standardGold,
                                                    shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                                  ),
                                                  label: const Text('MORE', style: TextStyle(fontWeight: FontWeight.bold)),
                                                ),
                                                const SizedBox(width: 8),
                                                
                                                TextButton.icon(
                                                  onPressed: () async {
                                                    final result = await showDialog<bool>(
                                                      context: context,
                                                      builder: (_) => BookEntryDialog(bookToEdit: book), 
                                                    );
                                                    
                                                    if (result == true) {
                                                      _triggerRefresh();
                                                    }
                                                  },
                                                  icon: const Icon(Icons.edit_rounded, size: 18),
                                                  style: TextButton.styleFrom(
                                                    foregroundColor: Colors.grey.shade700,
                                                    shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                                  ),
                                                  label: const Text('EDIT', style: TextStyle(fontWeight: FontWeight.bold)),
                                                ),
                                                const SizedBox(width: 8),

                                                TextButton.icon(
                                                  onPressed: () async {
                                                    if (!isAvailable) {
                                                      showDialog(
                                                        context: context,
                                                        builder: (BuildContext context) {
                                                          return AlertDialog(
                                                            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                                            title: const Row(
                                                              children: [
                                                                Icon(Icons.error_outline, color: Colors.red),
                                                                SizedBox(width: 10),
                                                                Text('Issue Denied', style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
                                                              ],
                                                            ),
                                                            content: const Text(
                                                              'This book is currently out of stock. A single copy cannot be assigned to multiple students simultaneously.',
                                                              style: TextStyle(fontSize: 14, height: 1.4),
                                                            ),
                                                            actions: [
                                                              TextButton(
                                                                onPressed: () => Navigator.of(context).pop(),
                                                                style: TextButton.styleFrom(
                                                                  foregroundColor: Colors.white,
                                                                  backgroundColor: Colors.grey.shade800,
                                                                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                                                ),
                                                                child: const Text('ACKNOWLEDGE'),
                                                              ),
                                                            ],
                                                          );
                                                        }
                                                      );
                                                      return; 
                                                    }

                                                    final result = await showDialog<bool>(
                                                      context: context,
                                                      builder: (_) => BorrowEntryDialog(book: book), 
                                                    );

                                                    if (result == true) {
                                                      _triggerRefresh();
                                                    }
                                                  }, 
                                                  icon: const Icon(Icons.bookmark_add_rounded, size: 18),
                                                  style: TextButton.styleFrom(
                                                    foregroundColor: isAvailable ? _darkGreen : Colors.red,
                                                    shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                                  ),
                                                  label: const Text(
                                                    'ISSUE', 
                                                    style: TextStyle(
                                                      fontWeight: FontWeight.bold,
                                                    )
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      );
                                    }).toList(),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      );
                    }
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}