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

import 'package:flutter/material.dart';
import 'package:intl/intl.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 BorrowingRecordsPanel extends StatefulWidget {
  const BorrowingRecordsPanel({super.key});

  @override
  State<BorrowingRecordsPanel> createState() =>
      _BorrowingRecordsPanelState();
}

class _BorrowingRecordsPanelState extends State<BorrowingRecordsPanel> {
  late Future<List<Map<String, dynamic>>> _recordsFuture;

  final List<Map<String, dynamic>> _allRecords = [];
  List<Map<String, dynamic>> _filteredRecords = [];

  final TextEditingController _searchController =
      TextEditingController();

  final ScrollController _verticalScrollController =
      ScrollController();

  final ScrollController _horizontalScrollController =
      ScrollController();

  String? _processingRefNo;
  String? _campusNotice;
  String _adminCampus = '';

  @override
  void initState() {
    super.initState();

    _recordsFuture = _fetchRecords();
    // The panel is recreated when the user changes library sections. Show the
    // saved snapshot first, then replace it with the latest server records.
    _refreshRecordsOnOpen();

    _searchController.addListener(_onSearchChanged);
  }

  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();

    _verticalScrollController.dispose();
    _horizontalScrollController.dispose();

    super.dispose();
  }

  // ============================================================
  // DATA HELPERS
  // ============================================================

  Map<String, dynamic>? _asMap(dynamic value) {
    if (value is Map<String, dynamic>) {
      return value;
    }

    if (value is Map) {
      return value.map(
        (key, value) => MapEntry(key.toString(), value),
      );
    }

    return null;
  }

  String _readString(
    Map<String, dynamic> record,
    List<String> possibleKeys,
  ) {
    for (final key in possibleKeys) {
      final value = record[key];

      if (value != null) {
        final text = value.toString().trim();

        if (text.isNotEmpty && text.toLowerCase() != 'null') {
          return text;
        }
      }
    }

    return '';
  }

  String _recordCampus(Map<String, dynamic> record) {
    // Try campus directly on borrowing record first.
    final directCampus = _readString(
      record,
      [
        'campus',
        'campus_name',
        'campusName',
        'branch',
        'branch_name',
        'location',
      ],
    );

    if (directCampus.isNotEmpty) {
      return directCampus;
    }

    // Some APIs may return the student as a nested object.
    final student = _asMap(record['student']);

    if (student != null) {
      return _readString(
        student,
        [
          'campus',
          'campus_name',
          'campusName',
          'branch',
          'branch_name',
        ],
      );
    }

    return '';
  }

  String _studentId(Map<String, dynamic> record) {
    final direct = _readString(
      record,
      [
        'student_id',
        'student_no',
        'student_number',
        'registration_number',
        'reg_no',
      ],
    );

    if (direct.isNotEmpty) return direct;

    final student = _asMap(record['student']);

    if (student != null) {
      return _readString(
        student,
        [
          'student_id',
          'student_no',
          'student_number',
          'registration_number',
          'reg_no',
          'id',
        ],
      );
    }

    return '';
  }

  String _bookId(Map<String, dynamic> record) {
    final direct = _readString(
      record,
      [
        'book_id',
        'bookId',
        'accession_no',
        'accession_number',
      ],
    );

    if (direct.isNotEmpty) return direct;

    final book = _asMap(record['book']);

    if (book != null) {
      return _readString(
        book,
        [
          'book_id',
          'id',
          'accession_no',
          'accession_number',
        ],
      );
    }

    return '';
  }

  String _bookTitle(Map<String, dynamic> record) {
    final direct = _readString(
      record,
      [
        'book_title',
        'book_name',
        'title',
      ],
    );

    if (direct.isNotEmpty) return direct;

    final book = _asMap(record['book']);

    if (book != null) {
      return _readString(
        book,
        [
          'book_title',
          'book_name',
          'title',
          'name',
        ],
      );
    }

    return '';
  }

  String _referenceNumber(Map<String, dynamic> record) {
    final ref = _readString(
      record,
      [
        'ref_no',
        'reference_no',
        'reference_number',
        'borrow_ref',
        'transaction_ref',
        'transaction_no',
      ],
    );

    if (ref.isNotEmpty) return ref;

    final id = _readString(
      record,
      [
        'id',
        'borrow_id',
        'borrowing_id',
        'transaction_id',
      ],
    );

    if (id.isNotEmpty) {
      return 'TX-$id';
    }

    return '';
  }

  String _borrowDate(Map<String, dynamic> record) {
    return _readString(
      record,
      [
        'borrow_date',
        'issue_date',
        'issued_at',
        'borrowed_at',
        'date_borrowed',
        'created_at',
      ],
    );
  }

  String _dueDate(Map<String, dynamic> record) {
    return _readString(
      record,
      [
        'due_date',
        'return_due_date',
        'expected_return_date',
        'date_due',
      ],
    );
  }

  String _returnDate(Map<String, dynamic> record) {
    return _readString(
      record,
      [
        'return_date',
        'returned_at',
        'date_returned',
        'actual_return_date',
      ],
    );
  }

  // ============================================================
  // CAMPUS NORMALIZATION
  // ============================================================

  String _normalizeCampus(String campus) {
    return campus
        .toLowerCase()
        .replaceAll('&', 'and')
        .replaceAll(RegExp(r'\bcampus\b'), '')
        .replaceAll(RegExp(r'[^a-z0-9]+'), ' ')
        .replaceAll(RegExp(r'\s+'), ' ')
        .trim();
  }

  bool _campusMatches(String adminCampus, String recordCampus) {
    final admin = _normalizeCampus(adminCampus);
    final record = _normalizeCampus(recordCampus);

    if (admin.isEmpty || record.isEmpty) {
      return false;
    }

    if (admin == record) {
      return true;
    }

    // Helps with values such as:
    // "Lusaka" and "Lusaka Campus"
    // "Main" and "Main Campus"
    if (admin.length >= 4 && record.contains(admin)) {
      return true;
    }

    if (record.length >= 4 && admin.contains(record)) {
      return true;
    }

    return false;
  }

  // ============================================================
  // LOAD BORROWING RECORDS
  // ============================================================

  Future<void> _refreshRecordsOnOpen() async {
    try {
      await _fetchRecords(refresh: true);
    } catch (error) {
      debugPrint('Could not refresh borrowing records on open: $error');
    }
  }

  Future<List<Map<String, dynamic>>> _fetchRecords({bool refresh = false}) async {
    try {
      final responses = await Future.wait<dynamic>([
        DatabaseService.getLocalUser(),
        LibraryApiService.getBorrowingRecords(refresh: refresh),
      ]);

      final LocalUser? currentUser =
          responses[0] as LocalUser?;

      final List<dynamic> rawRecords =
          responses[1] as List<dynamic>;

      // Convert dynamic JSON records into proper maps.
      final records = rawRecords
          .map(_asMap)
          .whereType<Map<String, dynamic>>()
          .toList();

      final adminCampus =
          (currentUser?.campus ?? '').toString().trim();

      _adminCampus = adminCampus;

      debugPrint(
        'LIBRARY: API returned ${records.length} borrowing records.',
      );

      debugPrint(
        'LIBRARY: Logged-in user campus = "$adminCampus"',
      );

      // Count how many records actually contain campus information.
      final recordsContainingCampus = records.where((record) {
        return _recordCampus(record).isNotEmpty;
      }).toList();

      List<Map<String, dynamic>> visibleRecords;

      String? notice;

      // ---------------------------------------------------------
      // IMPORTANT:
      // Do NOT blindly remove every record if PHP does not return
      // a campus field.
      // ---------------------------------------------------------

      if (records.isEmpty) {
        visibleRecords = [];
        notice = null;
      } else if (adminCampus.isEmpty) {
        // No local campus information available.
        //
        // We allow API results to display because the backend should
        // already enforce authorization/campus access.
        visibleRecords = records;

        notice =
            'Your local user profile does not contain a campus value. '
            'Showing the records returned by the server.';

        debugPrint(
          'LIBRARY WARNING: Current user has no campus value.',
        );
      } else if (recordsContainingCampus.isEmpty) {
        // PHP returned records, but none contains campus/campus_name.
        //
        // Previously your code returned FALSE here for every record,
        // causing the entire table to appear empty.
        visibleRecords = records;

        notice =
            'The server returned ${records.length} record(s), but no '
            'campus field was included. The records are being displayed '
            'using server-side permissions.';

        debugPrint(
          'LIBRARY WARNING: API records do not contain a campus field.',
        );
      } else {
        // Campus information exists, therefore safely filter it.
        visibleRecords = records.where((record) {
          final recordCampus = _recordCampus(record);

          return _campusMatches(
            adminCampus,
            recordCampus,
          );
        }).toList();

        if (visibleRecords.isEmpty && records.isNotEmpty) {
          final availableCampuses = recordsContainingCampus
              .map(_recordCampus)
              .where((campus) => campus.isNotEmpty)
              .toSet()
              .join(', ');

          notice =
              'The server returned ${records.length} record(s), but none '
              'matched your campus "$adminCampus". '
              'Server campus values: $availableCampuses';

          debugPrint(
            'LIBRARY CAMPUS MISMATCH: '
            'Admin="$adminCampus", '
            'Server campuses="$availableCampuses"',
          );
        }
      }

      final filtered = _filterList(
        visibleRecords,
        _searchController.text,
      );

      if (mounted) {
        setState(() {
          _allRecords
            ..clear()
            ..addAll(visibleRecords);

          _filteredRecords = filtered;

          _campusNotice = notice;
        });
      }

      debugPrint(
        'LIBRARY: ${visibleRecords.length} record(s) available '
        'after campus filtering.',
      );

      return visibleRecords;
    } catch (e, stackTrace) {
      debugPrint(
        'LIBRARY ERROR: Failed to load borrowing records: $e',
      );

      debugPrintStack(
        stackTrace: stackTrace,
      );

      throw Exception(
        'Failed to load borrowing records: $e',
      );
    }
  }

  // ============================================================
  // REFRESH
  // ============================================================

  void _triggerRefresh() {
    if (!mounted) return;

    final newFuture = _fetchRecords(refresh: true);

    setState(() {
      _recordsFuture = newFuture;
    });
  }

  // ============================================================
  // SEARCH
  // ============================================================

  void _onSearchChanged() {
    final results = _filterList(
      _allRecords,
      _searchController.text,
    );

    if (!mounted) return;

    setState(() {
      _filteredRecords = results;
    });
  }

  List<Map<String, dynamic>> _filterList(
    List<Map<String, dynamic>> records,
    String query,
  ) {
    final search = query.trim().toLowerCase();

    if (search.isEmpty) {
      return List<Map<String, dynamic>>.from(records);
    }

    return records.where((record) {
      final reference =
          _referenceNumber(record).toLowerCase();

      final student =
          _studentId(record).toLowerCase();

      final bookId =
          _bookId(record).toLowerCase();

      final bookTitle =
          _bookTitle(record).toLowerCase();

      final status = _readString(
        record,
        ['status', 'borrow_status', 'transaction_status'],
      ).toLowerCase();

      return reference.contains(search) ||
          student.contains(search) ||
          bookId.contains(search) ||
          bookTitle.contains(search) ||
          status.contains(search);
    }).toList();
  }

  // ============================================================
  // DATE FORMATTING
  // ============================================================

  String _formatDate(String rawDate) {
    if (rawDate.trim().isEmpty) {
      return '--';
    }

    try {
      final parsed = DateTime.parse(rawDate);

      return DateFormat('yyyy-MM-dd').format(parsed);
    } catch (_) {
      return rawDate;
    }
  }

  bool _isDateOverdue(String rawDate) {
    if (rawDate.trim().isEmpty) return false;

    final parsed = DateTime.tryParse(rawDate);

    if (parsed == null) return false;

    final dueDate = DateTime(
      parsed.year,
      parsed.month,
      parsed.day,
    );

    final now = DateTime.now();

    final today = DateTime(
      now.year,
      now.month,
      now.day,
    );

    return dueDate.isBefore(today);
  }

  // ============================================================
  // STATUS
  // ============================================================

  String _getRecordStatus(
    Map<String, dynamic> record,
  ) {
    final rawStatus = _readString(
      record,
      [
        'status',
        'borrow_status',
        'transaction_status',
      ],
    ).toUpperCase();

    final returnDate = _returnDate(record);

    // Return date is stronger evidence that the book was returned.
    if (returnDate.isNotEmpty) {
      return 'Returned';
    }

    if ([
      'RETURNED',
      'RETURN',
      'COMPLETED',
      'CLOSED',
    ].contains(rawStatus)) {
      return 'Returned';
    }

    final dueDate = _dueDate(record);

    if (_isDateOverdue(dueDate)) {
      return 'Overdue';
    }

    if (rawStatus == 'OVERDUE') {
      return 'Overdue';
    }

    return 'Active';
  }

  // ============================================================
  // RETURN BOOK
  // ============================================================

  Future<void> _confirmReturn(
    String referenceNumber,
    String bookTitle,
  ) async {
    if (referenceNumber.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'This transaction does not contain a valid reference number.',
          ),
          backgroundColor: Colors.redAccent,
        ),
      );

      return;
    }

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (dialogContext) {
        return AlertDialog(
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.zero,
          ),
          title: const Row(
            children: [
              Icon(
                Icons.assignment_return_rounded,
                color: _darkGreen,
              ),
              SizedBox(width: 12),
              Text('Confirm Book Return'),
            ],
          ),
          content: Text(
            bookTitle.isEmpty
                ? 'Mark transaction $referenceNumber as returned?'
                : 'Mark "$bookTitle" as returned?\n\n'
                    'Transaction: $referenceNumber',
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(dialogContext).pop(false);
              },
              child: const Text('CANCEL'),
            ),
            ElevatedButton.icon(
              onPressed: () {
                Navigator.of(dialogContext).pop(true);
              },
              icon: const Icon(
                Icons.keyboard_return_rounded,
              ),
              label: const Text('RETURN BOOK'),
              style: ElevatedButton.styleFrom(
                backgroundColor: _darkGreen,
                foregroundColor: Colors.white,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.zero,
                ),
              ),
            ),
          ],
        );
      },
    );

    if (confirmed == true && mounted) {
      await _processReturn(referenceNumber);
    }
  }

  Future<void> _processReturn(
    String referenceNumber,
  ) async {
    if (_processingRefNo != null) return;

    setState(() {
      _processingRefNo = referenceNumber;
    });

    try {
      await LibraryApiService.returnBook(
        referenceNumber,
      );

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'Book successfully returned. '
            'Transaction: $referenceNumber',
          ),
          backgroundColor: _darkGreen,
          behavior: SnackBarBehavior.floating,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.zero,
          ),
        ),
      );

      _triggerRefresh();
    } catch (e) {
      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'Unable to return book: $e',
          ),
          backgroundColor: Colors.redAccent,
          behavior: SnackBarBehavior.floating,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.zero,
          ),
        ),
      );
    } finally {
      if (mounted) {
        setState(() {
          _processingRefNo = null;
        });
      }
    }
  }

  // ============================================================
  // ERROR STATE
  // ============================================================

  Widget _buildErrorState(Object error) {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.cloud_off_rounded,
              size: 54,
              color: Colors.redAccent,
            ),
            const SizedBox(height: 16),
            const Text(
              'Unable to Load Borrowing Records',
              style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            SelectableText(
              error.toString(),
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.grey.shade700,
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              onPressed: _triggerRefresh,
              icon: const Icon(Icons.refresh),
              label: const Text('TRY AGAIN'),
              style: ElevatedButton.styleFrom(
                backgroundColor: _darkGreen,
                foregroundColor: Colors.white,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.zero,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ============================================================
  // EMPTY STATE
  // ============================================================

  Widget _buildEmptyState() {
    final searching =
        _searchController.text.trim().isNotEmpty;

    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              searching
                  ? Icons.search_off_rounded
                  : Icons.library_books_outlined,
              size: 58,
              color: Colors.grey.shade400,
            ),
            const SizedBox(height: 16),
            Text(
              searching
                  ? 'No Matching Records'
                  : 'No Borrowing Records Found',
              style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade800,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              searching
                  ? 'No borrowing record matches '
                      '"${_searchController.text}".'
                  : (_campusNotice ??
                      (_adminCampus.isNotEmpty
                          ? 'No circulation records are currently '
                              'available for $_adminCampus.'
                          : 'No circulation records are currently available.')),
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.grey.shade600,
              ),
            ),
            if (!searching) ...[
              const SizedBox(height: 20),
              OutlinedButton.icon(
                onPressed: _triggerRefresh,
                icon: const Icon(Icons.refresh),
                label: const Text('REFRESH'),
                style: OutlinedButton.styleFrom(
                  foregroundColor: _darkGreen,
                  side: const BorderSide(
                    color: _darkGreen,
                  ),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  // ============================================================
  // MAIN UI
  // ============================================================

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment:
            CrossAxisAlignment.stretch,
        children: [
          // ====================================================
          // HEADER
          // ====================================================

          Wrap(
            alignment: WrapAlignment.spaceBetween,
            crossAxisAlignment:
                WrapCrossAlignment.center,
            spacing: 16,
            runSpacing: 16,
            children: [
              Column(
                crossAxisAlignment:
                    CrossAxisAlignment.start,
                children: [
                  Text(
                    'CIRCULATION & BORROWING',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w900,
                      color: Colors.grey.shade800,
                      letterSpacing: 1.5,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    '${_filteredRecords.length} shown • '
                    '${_allRecords.length} total',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),

              Wrap(
                spacing: 12,
                runSpacing: 12,
                crossAxisAlignment:
                    WrapCrossAlignment.center,
                children: [
                  Container(
                    height: 56,
                    width: 56,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(
                        color: Colors.grey.shade300,
                      ),
                    ),
                    child: IconButton(
                      icon: const Icon(
                        Icons.refresh_rounded,
                        color: _darkGreen,
                      ),
                      onPressed: _triggerRefresh,
                      tooltip: 'Refresh Records',
                    ),
                  ),

                  SizedBox(
                    width: 320,
                    child: TextField(
                      controller: _searchController,
                      decoration: InputDecoration(
                        hintText:
                            'Search ref, student or book...',
                        prefixIcon: const Icon(
                          Icons.search,
                          color: Colors.grey,
                        ),
                        suffixIcon: _searchController
                                .text
                                .isNotEmpty
                            ? IconButton(
                                tooltip: 'Clear search',
                                icon: const Icon(
                                  Icons.close,
                                ),
                                onPressed: () {
                                  _searchController.clear();
                                },
                              )
                            : null,
                        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,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),

          // Campus/API warning.
          if (_campusNotice != null &&
              _allRecords.isNotEmpty) ...[
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.amber.shade50,
                border: Border.all(
                  color: Colors.amber.shade300,
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline,
                    color: Colors.amber.shade900,
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      _campusNotice!,
                      style: TextStyle(
                        color: Colors.amber.shade900,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],

          const SizedBox(height: 20),

          // ====================================================
          // TABLE
          // ====================================================

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

                  if (snapshot.hasError) {
                    return _buildErrorState(
                      snapshot.error!,
                    );
                  }

                  if (_filteredRecords.isEmpty) {
                    return _buildEmptyState();
                  }

                  return LayoutBuilder(
                    builder: (
                      context,
                      constraints,
                    ) {
                      return Theme(
                        data: Theme.of(context).copyWith(
                          scrollbarTheme:
                              ScrollbarThemeData(
                            thumbColor:
                                WidgetStateProperty.all(
                              _darkGreen.withOpacity(
                                0.65,
                              ),
                            ),
                            trackColor:
                                WidgetStateProperty.all(
                              Colors.grey.shade100,
                            ),
                            trackBorderColor:
                                WidgetStateProperty.all(
                              Colors.grey.shade300,
                            ),
                            thickness:
                                WidgetStateProperty.all(
                              11,
                            ),
                            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,
                              notificationPredicate:
                                  (notification) {
                                return notification
                                        .metrics
                                        .axis ==
                                    Axis.horizontal;
                              },
                              child:
                                  SingleChildScrollView(
                                controller:
                                    _horizontalScrollController,
                                scrollDirection:
                                    Axis.horizontal,
                                child:
                                    ConstrainedBox(
                                  constraints:
                                      BoxConstraints(
                                    minWidth:
                                        constraints
                                            .maxWidth,
                                  ),
                                  child: DataTable(
                                    columnSpacing: 30,
                                    horizontalMargin: 24,
                                    headingRowHeight: 58,
                                    dataRowMinHeight: 68,
                                    dataRowMaxHeight: 68,
                                    dividerThickness: 1,

                                    headingRowColor:
                                        WidgetStateProperty
                                            .all(
                                      _darkGreen,
                                    ),

                                    headingTextStyle:
                                        const TextStyle(
                                      color: Colors.white,
                                      fontWeight:
                                          FontWeight.bold,
                                      letterSpacing: 0.5,
                                    ),

                                    border: TableBorder(
                                      horizontalInside:
                                          BorderSide(
                                        color: Colors
                                            .grey
                                            .shade300,
                                      ),
                                      verticalInside:
                                          BorderSide(
                                        color: Colors
                                            .grey
                                            .shade200,
                                      ),
                                    ),

                                    columns: const [
                                      DataColumn(
                                        label: Text(
                                          'REF NO.',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'STUDENT ID',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'BOOK ID / TITLE',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'BORROW DATE',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'DUE DATE',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'STATUS',
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          'ACTION',
                                        ),
                                      ),
                                    ],

                                    rows:
                                        _filteredRecords
                                            .map(
                                      (record) {
                                        final refNo =
                                            _referenceNumber(
                                          record,
                                        );

                                        final studentId =
                                            _studentId(
                                          record,
                                        );

                                        final bookId =
                                            _bookId(
                                          record,
                                        );

                                        final bookTitle =
                                            _bookTitle(
                                          record,
                                        );

                                        String
                                            bookDisplay;

                                        if (bookId
                                                .isNotEmpty &&
                                            bookTitle
                                                .isNotEmpty) {
                                          bookDisplay =
                                              '$bookId — $bookTitle';
                                        } else if (bookTitle
                                            .isNotEmpty) {
                                          bookDisplay =
                                              bookTitle;
                                        } else if (bookId
                                            .isNotEmpty) {
                                          bookDisplay =
                                              bookId;
                                        } else {
                                          bookDisplay =
                                              '--';
                                        }

                                        final
                                            borrowDateRaw =
                                            _borrowDate(
                                          record,
                                        );

                                        final dueDateRaw =
                                            _dueDate(
                                          record,
                                        );

                                        final
                                            currentStatus =
                                            _getRecordStatus(
                                          record,
                                        );

                                        final isOverdue =
                                            currentStatus ==
                                                'Overdue';

                                        final isReturned =
                                            currentStatus ==
                                                'Returned';

                                        final canReturn =
                                            currentStatus ==
                                                    'Active' ||
                                                currentStatus ==
                                                    'Overdue';

                                        Color
                                            statusColor;
                                        Color bgColor;

                                        if (isReturned) {
                                          statusColor =
                                              Colors
                                                  .green
                                                  .shade700;

                                          bgColor =
                                              Colors
                                                  .green
                                                  .shade50;
                                        } else if (isOverdue) {
                                          statusColor =
                                              Colors.red;

                                          bgColor =
                                              Colors
                                                  .red
                                                  .shade50;
                                        } else {
                                          statusColor =
                                              _standardGold;

                                          bgColor =
                                              Colors
                                                  .orange
                                                  .shade50;
                                        }

                                        final processing =
                                            _processingRefNo ==
                                                refNo;

                                        return DataRow(
                                          key: ValueKey(
                                            '$refNo-$studentId-$bookId-$borrowDateRaw',
                                          ),
                                          cells: [
                                            DataCell(
                                              Text(
                                                refNo
                                                        .isEmpty
                                                    ? '--'
                                                    : refNo,
                                                style:
                                                    const TextStyle(
                                                  fontWeight:
                                                      FontWeight
                                                          .w700,
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              Text(
                                                studentId
                                                        .isEmpty
                                                    ? '--'
                                                    : studentId,
                                                style:
                                                    const TextStyle(
                                                  fontWeight:
                                                      FontWeight
                                                          .w500,
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              ConstrainedBox(
                                                constraints:
                                                    const BoxConstraints(
                                                  maxWidth:
                                                      320,
                                                ),
                                                child: Text(
                                                  bookDisplay,
                                                  overflow:
                                                      TextOverflow
                                                          .ellipsis,
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              Text(
                                                _formatDate(
                                                  borrowDateRaw,
                                                ),
                                                style:
                                                    TextStyle(
                                                  color: Colors
                                                      .grey
                                                      .shade800,
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              Text(
                                                _formatDate(
                                                  dueDateRaw,
                                                ),
                                                style:
                                                    TextStyle(
                                                  fontWeight:
                                                      isOverdue
                                                          ? FontWeight
                                                              .bold
                                                          : FontWeight
                                                              .normal,
                                                  color:
                                                      isOverdue
                                                          ? Colors
                                                              .red
                                                          : Colors
                                                              .black87,
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              Container(
                                                padding:
                                                    const EdgeInsets
                                                        .symmetric(
                                                  horizontal:
                                                      14,
                                                  vertical:
                                                      7,
                                                ),
                                                decoration:
                                                    BoxDecoration(
                                                  color:
                                                      bgColor,
                                                  border:
                                                      Border.all(
                                                    color:
                                                        statusColor,
                                                  ),
                                                ),
                                                child: Text(
                                                  currentStatus
                                                      .toUpperCase(),
                                                  style:
                                                      TextStyle(
                                                    color:
                                                        statusColor,
                                                    fontWeight:
                                                        FontWeight
                                                            .bold,
                                                    fontSize:
                                                        11,
                                                    letterSpacing:
                                                        0.5,
                                                  ),
                                                ),
                                              ),
                                            ),

                                            DataCell(
                                              canReturn
                                                  ? TextButton
                                                      .icon(
                                                      onPressed:
                                                          (_processingRefNo !=
                                                                      null ||
                                                                  refNo
                                                                      .isEmpty)
                                                              ? null
                                                              : () {
                                                                  _confirmReturn(
                                                                    refNo,
                                                                    bookTitle,
                                                                  );
                                                                },
                                                      icon: processing
                                                          ? const SizedBox(
                                                              height: 16,
                                                              width: 16,
                                                              child:
                                                                  CircularProgressIndicator(
                                                                strokeWidth:
                                                                    2,
                                                              ),
                                                            )
                                                          : const Icon(
                                                              Icons
                                                                  .keyboard_return_rounded,
                                                              size:
                                                                  18,
                                                            ),
                                                      label: Text(
                                                        processing
                                                            ? 'RETURNING...'
                                                            : 'RETURN',
                                                        style:
                                                            const TextStyle(
                                                          fontWeight:
                                                              FontWeight.bold,
                                                        ),
                                                      ),
                                                      style:
                                                          TextButton
                                                              .styleFrom(
                                                        foregroundColor:
                                                            _darkGreen,
                                                        shape:
                                                            const RoundedRectangleBorder(
                                                          borderRadius:
                                                              BorderRadius.zero,
                                                        ),
                                                      ),
                                                    )
                                                  : const Padding(
                                                      padding:
                                                          EdgeInsets
                                                              .only(
                                                        left:
                                                            16,
                                                      ),
                                                      child:
                                                          Text(
                                                        '--',
                                                        style:
                                                            TextStyle(
                                                          color:
                                                              Colors.grey,
                                                        ),
                                                      ),
                                                    ),
                                            ),
                                          ],
                                        );
                                      },
                                    ).toList(),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
