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

import 'package:flutter/material.dart';
import '../../../../core/networks/library_api_service.dart'; 

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

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

  @override
  State<AllRecordsPanel> createState() => _AllRecordsPanelState();
}

class _AllRecordsPanelState extends State<AllRecordsPanel> {
  late Future<void> _dataFuture;
  
  // Statistics State
  int _totalGlobalStudents = 0;
  int _totalGlobalBooks = 0;
  int _totalGlobalBorrowings = 0;
  Map<String, Map<String, int>> _campusStats = {};

  final ScrollController _verticalScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _dataFuture = _fetchGlobalData();
  }

  @override
  void dispose() {
    _verticalScrollController.dispose();
    super.dispose();
  }

  String _normalizeCampus(String? input) {
    if (input == null || input.trim().isEmpty) return 'Main Campus';
    final s = input.trim();
    return s.split(' ').map((word) => word.isNotEmpty ? '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}' : '').join(' ');
  }

  Future<void> _fetchGlobalData() async {
    try {
      final responses = await Future.wait([
        LibraryApiService.getBorrowingRecords(),
        LibraryApiService.getStudents(),
        LibraryApiService.getBooks(),
      ]);
      
      final records = responses[0] as List<dynamic>;
      final students = responses[1] as List<dynamic>;
      final books = responses[2] as List<dynamic>;

      int gStudents = students.length;
      int gBooks = 0;
      int gBorrowings = 0; 
      Map<String, Map<String, int>> stats = {};

      void initCampus(String c) {
        if (!stats.containsKey(c)) {
          stats[c] = {'students': 0, 'books': 0, 'borrowings': 0};
        }
      }

      // Aggregate Students
      for (var s in students) {
        String c = _normalizeCampus(s['campus']?.toString() ?? s['campus_name']?.toString());
        initCampus(c);
        stats[c]!['students'] = stats[c]!['students']! + 1;
      }

      // Aggregate Books with strict fallback
      for (var b in books) {
        String c = _normalizeCampus(b['campus']?.toString() ?? b['campus_name']?.toString());
        initCampus(c);
        
        int parsedCopies = int.tryParse(b['total_copies']?.toString() ?? b['copies']?.toString() ?? '0') ?? 0;
        int copies = parsedCopies > 0 ? parsedCopies : 1; 
        
        gBooks += copies;
        stats[c]!['books'] = stats[c]!['books']! + copies;
      }

      // Aggregate Borrowings (STRICTLY ACTIVE ONLY)
      for (var r in records) {
        String currentStatus = r['status']?.toString() ?? 'Active';
        
        if (currentStatus.toUpperCase() != 'RETURNED') {
          String c = _normalizeCampus(r['campus']?.toString() ?? r['campus_name']?.toString());
          initCampus(c);
          stats[c]!['borrowings'] = stats[c]!['borrowings']! + 1;
          gBorrowings++;
        }
      }

      if (mounted) {
        setState(() {
          _totalGlobalStudents = gStudents;
          _totalGlobalBooks = gBooks;
          _totalGlobalBorrowings = gBorrowings;
          _campusStats = stats;
        });
      }
    } catch (e) {
      throw Exception('Failed to load global records: $e');
    }
  }

  void _triggerRefresh() {
    setState(() {
      _dataFuture = _fetchGlobalData();
    });
  }

  String _calculatePercentage(int part, int total) {
    if (total == 0) return '0%';
    double percentage = (part / total) * 100;
    return '${percentage.toStringAsFixed(1)}%';
  }

  Widget _buildSummaryCard(String title, int count, IconData icon, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(24),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade300, width: 1.5),
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 10, offset: const Offset(0, 4))],
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(color: color.withOpacity(0.1), shape: BoxShape.circle),
              child: Icon(icon, color: color, size: 28),
            ),
            const SizedBox(width: 20),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(title.toUpperCase(), style: TextStyle(color: Colors.grey.shade600, fontSize: 12, fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                const SizedBox(height: 6),
                Text(count.toString(), style: TextStyle(color: color, fontSize: 26, fontWeight: FontWeight.w900)),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildPercentageBadge(String percentage, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        percentage,
        style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 11),
      ),
    );
  }

  @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: [
          Wrap(
            alignment: WrapAlignment.spaceBetween,
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 16.0,
            runSpacing: 16.0,
            children: [
              Text(
                'GLOBAL LIBRARY STATISTICS',
                style: TextStyle(
                  fontSize: 18, 
                  fontWeight: FontWeight.w900, 
                  color: Colors.grey.shade800, 
                  letterSpacing: 1.5
                ),
              ),
              Container(
                height: 56, 
                width: 56,
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.grey.shade300, width: 1),
                ),
                child: IconButton(
                  icon: const Icon(Icons.refresh_rounded, color: _darkGreen),
                  onPressed: _triggerRefresh,
                  tooltip: 'Refresh Statistics',
                  splashRadius: 24,
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),

          Expanded(
            child: FutureBuilder<void>(
              future: _dataFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting && _campusStats.isEmpty) {
                  return const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(_darkGreen)));
                }

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

                return SingleChildScrollView(
                  controller: _verticalScrollController,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // --- SUMMARY CARDS ---
                      if (isDesktop)
                        Row(
                          children: [
                            _buildSummaryCard('Global Students', _totalGlobalStudents, Icons.people_alt_rounded, Colors.blue.shade700),
                            const SizedBox(width: 16),
                            _buildSummaryCard('Global Inventory', _totalGlobalBooks, Icons.library_books_rounded, _darkGreen),
                            const SizedBox(width: 16),
                            _buildSummaryCard('Active Borrowings', _totalGlobalBorrowings, Icons.sync_alt_rounded, _standardGold),
                          ],
                        )
                      else
                        Column(
                          children: [
                            Row(children: [_buildSummaryCard('Global Students', _totalGlobalStudents, Icons.people_alt_rounded, Colors.blue.shade700)]),
                            const SizedBox(height: 16),
                            Row(children: [_buildSummaryCard('Global Inventory', _totalGlobalBooks, Icons.library_books_rounded, _darkGreen)]),
                            const SizedBox(height: 16),
                            Row(children: [_buildSummaryCard('Active Borrowings', _totalGlobalBorrowings, Icons.sync_alt_rounded, _standardGold)]),
                          ],
                        ),

                      const SizedBox(height: 24),

                      // --- 🚀 UPGRADED: 100% WIDTH FLEX TABLE ---
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.grey.shade300, width: 1.5),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                              color: Colors.grey.shade50,
                              child: Text(
                                'CAMPUS PERFORMANCE BREAKDOWN',
                                style: TextStyle(color: Colors.grey.shade800, fontWeight: FontWeight.w900, fontSize: 13, letterSpacing: 1.0),
                              ),
                            ),
                            const Divider(height: 1, thickness: 1),
                            // Native Table widget forces 100% width and calculates columns proportionally
                            Table(
                              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                              border: TableBorder(
                                horizontalInside: BorderSide(color: Colors.grey.shade200, width: 1),
                                verticalInside: BorderSide(color: Colors.grey.shade200, width: 1),
                              ),
                              columnWidths: const {
                                0: FlexColumnWidth(2.5),
                                1: FlexColumnWidth(2),
                                2: FlexColumnWidth(2),
                                3: FlexColumnWidth(2),
                              },
                              children: [
                                TableRow(
                                  decoration: BoxDecoration(color: _darkGreen.withOpacity(0.05)),
                                  children: [
                                    _buildTableCell('CAMPUS NAME', isHeader: true),
                                    _buildTableCell('REGISTERED STUDENTS', isHeader: true),
                                    _buildTableCell('BOOK INVENTORY', isHeader: true),
                                    _buildTableCell('ACTIVE BORROWINGS', isHeader: true),
                                  ],
                                ),
                                ..._campusStats.entries.map((entry) {
                                  final campusName = entry.key;
                                  final students = entry.value['students'] ?? 0;
                                  final books = entry.value['books'] ?? 0;
                                  final borrowings = entry.value['borrowings'] ?? 0;

                                  return TableRow(
                                    children: [
                                      _buildTableCell(campusName, isBold: true),
                                      _buildMetricCell(students, _calculatePercentage(students, _totalGlobalStudents), Colors.blue.shade700),
                                      _buildMetricCell(books, _calculatePercentage(books, _totalGlobalBooks), _darkGreen),
                                      _buildMetricCell(borrowings, _calculatePercentage(borrowings, _totalGlobalBorrowings), _standardGold),
                                    ],
                                  );
                                }),
                              ],
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 48),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // --- REUSABLE TABLE WIDGET COMPONENTS ---
  Widget _buildTableCell(String text, {bool isHeader = false, bool isBold = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 24),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: isHeader ? FontWeight.bold : (isBold ? FontWeight.w700 : FontWeight.w500),
          fontSize: isHeader ? 12 : 14,
          color: isHeader ? _darkGreen : Colors.black87,
          letterSpacing: isHeader ? 0.5 : 0,
        ),
      ),
    );
  }

  Widget _buildMetricCell(int count, String percentage, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(count.toString(), style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 15)),
          const SizedBox(width: 12),
          _buildPercentageBadge(percentage, color),
        ],
      ),
    );
  }
}