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

// 🚀 NO CHANGES NEEDED: This UI perfectly delegates all network traffic 
// to LibraryApiService, meaning it automatically talks to the new PHP backend!

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

  @override
  State<StudentsDirectoryPanel> createState() => _StudentsDirectoryPanelState();
}

class _StudentsDirectoryPanelState extends State<StudentsDirectoryPanel> {
  late Future<List<dynamic>> _studentsFuture;
  
  // State variables for search filtering
  List<dynamic> _allStudents = [];
  List<dynamic> _filteredStudents = [];
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _studentsFuture = _fetchStudents();
    _searchController.addListener(_onSearchChanged);
  }

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

  Future<List<dynamic>> _fetchStudents() async {
    try {
      // 🚀 Fetch current user, students, and borrowing records concurrently
      final responses = await Future.wait([
        DatabaseService.getLocalUser(),
        LibraryApiService.getStudents(),
        LibraryApiService.getBorrowingRecords(),
      ]);

      final LocalUser? currentUser = responses[0] as LocalUser?;
      final rawStudents = 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 students list to match the admin's campus
      final campusStudents = rawStudents.where((s) {
        final c = (s['campus'] ?? s['campus_name'] ?? '').toString().toLowerCase().trim();
        if (c.isEmpty) return false;
        return c == adminCampus || c.contains(adminCampus) || adminCampus.contains(c);
      }).toList();

      // Map active borrowings by student ID
      final Map<String, int> activeBorrowsMap = {};
      for (var record in rawRecords) {
        final status = record['status']?.toString().toUpperCase() ?? '';
        if (status == 'BORROWED' || status == 'ISSUED') {
          final studentId = record['student_id']?.toString() ?? '';
          if (studentId.isNotEmpty) {
            activeBorrowsMap[studentId] = (activeBorrowsMap[studentId] ?? 0) + 1;
          }
        }
      }

      // Inject the calculated borrows back into the strictly filtered student objects
      final students = campusStudents.map((s) {
        final mutableStudent = Map<String, dynamic>.from(s);
        final sId = mutableStudent['id']?.toString() ?? '';
        mutableStudent['active_borrows'] = activeBorrowsMap[sId] ?? 0;
        return mutableStudent;
      }).toList();

      setState(() {
        _allStudents = students;
        _filterStudents(_searchController.text); 
      });
      
      return students;
    } catch (e) {
      throw Exception('Failed to load students: $e');
    }
  }

  void _triggerRefresh() {
    setState(() {
      _studentsFuture = _fetchStudents();
    });
  }

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

  void _filterStudents(String query) {
    if (query.isEmpty) {
      setState(() {
        _filteredStudents = List.from(_allStudents);
      });
    } else {
      final lowercaseQuery = query.toLowerCase();
      setState(() {
        _filteredStudents = _allStudents.where((student) {
          final id = student['id']?.toString().toLowerCase() ?? '';
          final name = student['name']?.toString().toLowerCase() ?? '';
          return id.contains(lowercaseQuery) || name.contains(lowercaseQuery);
        }).toList();
      });
    }
  }

  // 🚀 Helper to trigger a loading spinner before showing a popup dialog
  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(); // Dismiss loader
      showDialogAction(); // Trigger the target dialog
    }
  }

  // --- VIEW RECORD DIALOG ---
  void _showViewDialog(BuildContext context, dynamic student) {
    showDialog(
      context: context,
      builder: (_) => Dialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor: Colors.white,
        child: Container(
          width: 450,
          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(
                      'STUDENT 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: [
                    _buildDetailRow('Student ID', student['id']?.toString() ?? 'N/A'),
                    const Divider(height: 32),
                    _buildDetailRow('Full Name', student['name']?.toString() ?? 'Unknown'),
                    const Divider(height: 32),
                    _buildDetailRow('Department', student['department']?.toString() ?? 'Unassigned'),
                    const Divider(height: 32),
                    _buildDetailRow('Campus', student['campus']?.toString() ?? student['campus_name']?.toString() ?? 'Main Campus'),
                    const Divider(height: 32),
                    _buildDetailRow('Email', student['email']?.toString() ?? 'N/A'),
                    const Divider(height: 32),
                    _buildDetailRow('Active Borrows', student['active_borrows']?.toString() ?? '0', isHighlight: true),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {bool isHighlight = false}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 120,
          child: Text(
            label.toUpperCase(),
            style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey.shade500, fontSize: 12, letterSpacing: 0.5),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: TextStyle(
              fontSize: 15,
              fontWeight: isHighlight ? FontWeight.bold : FontWeight.w500,
              color: isHighlight ? _darkGreen : Colors.grey.shade800,
            ),
          ),
        ),
      ],
    );
  }

  // --- QR CODE DIALOG ---
  void _showQrDialog(BuildContext context, dynamic student) {
    final String formattedInfo = '''
Rockview University Library
--------------------------------
ID: ${student['id']?.toString() ?? 'N/A'}
Name: ${student['name']?.toString() ?? 'Unknown'}
Dept: ${student['department']?.toString() ?? 'Unassigned'}
Campus: ${student['campus']?.toString() ?? student['campus_name']?.toString() ?? 'Main Campus'}
Email: ${student['email']?.toString() ?? 'N/A'}
'''.trim();

    showDialog(
      context: context,
      builder: (_) => Dialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor: Colors.white,
        child: Container(
          width: 380,
          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('DIGITAL ID SCAN', 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.symmetric(vertical: 40.0, horizontal: 32.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300, width: 2), color: Colors.white),
                      child: QrImageView(
                        data: formattedInfo,
                        version: QrVersions.auto,
                        size: 200.0,
                        eyeStyle: const QrEyeStyle(eyeShape: QrEyeShape.square, color: _darkGreen),
                        dataModuleStyle: const QrDataModuleStyle(dataModuleShape: QrDataModuleShape.square, color: Colors.black87),
                      ),
                    ),
                    const SizedBox(height: 24),
                    Text(
                      'Scan this code to verify student details or process transactions.',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 13, color: Colors.grey.shade600, height: 1.4),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // --- RESPONSIVE HEADER ---
          Wrap(
            alignment: WrapAlignment.spaceBetween,
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 16.0,
            runSpacing: 16.0,
            children: [
              Text(
                'STUDENT RECORDS',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: Colors.grey.shade800, letterSpacing: 1.5),
              ),
              Wrap(
                spacing: 16.0,
                runSpacing: 16.0,
                crossAxisAlignment: WrapCrossAlignment.center,
                children: [
                  SizedBox(
                    width: 320,
                    child: TextField(
                      controller: _searchController,
                      decoration: InputDecoration(
                        hintText: 'Search Student ID or Name...',
                        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 StudentEntryDialog(studentData: null),
                      );
                      if (result == true) _triggerRefresh();
                    },
                    icon: const Icon(Icons.person_add_rounded, color: Colors.white),
                    label: const Text('ADD NEW STUDENT', 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),

          // --- DATA TABLE WRAPPER ---
          Expanded(
            child: Container(
              // Outer border to enclose the table cleanly
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.grey.shade300, width: 1.5),
              ),
              child: FutureBuilder<List<dynamic>>(
                future: _studentsFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting && _allStudents.isEmpty) {
                    return const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(_darkGreen)));
                  }

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

                  if (_filteredStudents.isEmpty) {
                    return Center(
                      child: Text(
                        _searchController.text.isEmpty ? 'No students found for your campus.' : 'No students match your search.',
                        style: const TextStyle(color: Colors.grey, fontStyle: FontStyle.italic),
                      ),
                    );
                  }

                  return LayoutBuilder(
                    builder: (context, constraints) {
                      return SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: ConstrainedBox(
                            constraints: BoxConstraints(minWidth: constraints.maxWidth),
                            child: DataTable(
                              columnSpacing: 30.0,
                              horizontalMargin: 24.0,
                              // Visible Excel-style cell borders inside the table
                              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: 70,
                              dataRowMaxHeight: 70,
                              dividerThickness: 1,
                              columns: const [
                                DataColumn(label: Text('STUDENT ID')),
                                DataColumn(label: Text('FULL NAME')),
                                DataColumn(label: Text('DEPARTMENT')),
                                DataColumn(label: Text('CAMPUS')),
                                DataColumn(label: Center(child: Text('ACTIVE BORROWS'))),
                                DataColumn(label: Text('ACCOUNT STATUS')),
                                DataColumn(label: Text('ACTIONS')),
                              ],
                              rows: _filteredStudents.map((student) {
                                final studentId = student['id']?.toString() ?? 'N/A';
                                final studentName = student['name']?.toString() ?? 'Unknown';
                                final department = student['department']?.toString() ?? 'Unassigned';
                                final campus = student['campus']?.toString() ?? student['campus_name']?.toString() ?? 'Main Campus';
                                
                                final int activeBorrows = int.tryParse(student['active_borrows']?.toString() ?? '0') ?? 0;
                                final String accountStatus = student['status']?.toString() ?? (activeBorrows > 2 ? 'Warning' : 'Active');
                                final bool isWarning = accountStatus.toUpperCase() == 'WARNING';

                                return DataRow(
                                  cells: [
                                    DataCell(Text(studentId, style: const TextStyle(fontWeight: FontWeight.w700))),
                                    DataCell(Text(studentName, style: const TextStyle(fontWeight: FontWeight.w500))),
                                    DataCell(Text(department)),
                                    DataCell(Text(campus, style: TextStyle(color: Colors.grey.shade700))),
                                    
                                    // Designed badge specifically for active borrows logic
                                    DataCell(
                                      Center(
                                        child: Container(
                                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                                          decoration: BoxDecoration(
                                            color: activeBorrows > 0 ? _standardGold.withOpacity(0.1) : Colors.grey.shade100,
                                            border: Border.all(color: activeBorrows > 0 ? _standardGold : Colors.grey.shade300),
                                            borderRadius: BorderRadius.circular(4),
                                          ),
                                          child: Text(
                                            activeBorrows.toString(),
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 15,
                                              color: activeBorrows > 0 ? _standardGold : Colors.grey.shade500,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                        decoration: BoxDecoration(
                                          color: isWarning ? Colors.red.shade50 : Colors.green.shade50,
                                          border: Border.all(color: isWarning ? Colors.red : Colors.green),
                                        ),
                                        child: Text(
                                          accountStatus,
                                          style: TextStyle(
                                            color: isWarning ? Colors.red : Colors.green.shade700,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 12,
                                            letterSpacing: 0.5,
                                          ),
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          TextButton(
                                            // 🚀 WRAPPED IN LOADING SPINNER
                                            onPressed: () => _showWithLoader(context, () => _showViewDialog(context, student)),
                                            style: TextButton.styleFrom(
                                              foregroundColor: _standardGold,
                                              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                            ),
                                            child: const Text('VIEW', style: TextStyle(fontWeight: FontWeight.bold)),
                                          ),
                                          const SizedBox(width: 8),
                                          TextButton(
                                            // 🚀 WRAPPED IN LOADING SPINNER
                                            onPressed: () => _showWithLoader(context, () async {
                                              final result = await showDialog<bool>(
                                                context: context,
                                                builder: (_) => StudentEntryDialog(studentData: student), 
                                              );
                                              if (result == true) _triggerRefresh();
                                            }),
                                            style: TextButton.styleFrom(
                                              foregroundColor: Colors.grey.shade700,
                                              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                            ),
                                            child: const Text('EDIT', style: TextStyle(fontWeight: FontWeight.bold)),
                                          ),
                                          const SizedBox(width: 8),
                                          TextButton.icon(
                                            // 🚀 WRAPPED IN LOADING SPINNER
                                            onPressed: () => _showWithLoader(context, () => _showQrDialog(context, student)),
                                            style: TextButton.styleFrom(
                                              foregroundColor: _darkGreen,
                                              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                            ),
                                            icon: const Icon(Icons.qr_code, size: 18),
                                            label: const Text('QR', style: TextStyle(fontWeight: FontWeight.bold)),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}