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

import 'package:flutter/material.dart';
import '../../../../core/networks/library_api_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 OtherCampusesPanel extends StatefulWidget {
  final String campusName;
  final LocalUser? currentUser; 

  const OtherCampusesPanel({super.key, required this.campusName, this.currentUser});

  @override
  State<OtherCampusesPanel> createState() => _OtherCampusesPanelState();
}

class _OtherCampusesPanelState extends State<OtherCampusesPanel> {
  late Future<Map<String, dynamic>> _dashboardDataFuture;
  bool _showStats = true; 

  @override
  void initState() {
    super.initState();
    _dashboardDataFuture = _fetchRemoteDashboardData();
  }

  @override
  void didUpdateWidget(covariant OtherCampusesPanel oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.campusName != widget.campusName) {
      setState(() {
        _dashboardDataFuture = _fetchRemoteDashboardData();
      });
    }
  }

  Future<Map<String, dynamic>> _fetchRemoteDashboardData() async {
    try {
      final responses = await Future.wait([
        LibraryApiService.getBooks(),
        LibraryApiService.getBorrowingRecords(),
        LibraryApiService.getStudents(),
      ]);

      final allBooks = responses[0] as List<dynamic>;
      final allRecords = responses[1] as List<dynamic>;
      final allStudents = responses[2] as List<dynamic>;

      final targetCampus = widget.campusName.toLowerCase().trim();

      // 🚀 STRICT FILTERING LOGIC: Completely ignores null/empty campuses and requires exact match
      bool matchesCampus(dynamic item) {
        final c = (item['campus'] ?? item['campus_name'] ?? '').toString().toLowerCase().trim();
        if (c.isEmpty) return false; // Prevents blank database entries from bleeding into stats
        return c == targetCampus || c.contains(targetCampus) || targetCampus.contains(c);
      }

      final campusBooks = allBooks.where(matchesCampus).toList();
      final campusRecords = allRecords.where(matchesCampus).toList();
      final campusStudents = allStudents.where(matchesCampus).toList();

      int activeBorrowings = 0;
      int overdueReturns = 0;
      final now = DateTime.now();

      for (var record in campusRecords) {
        final status = record['status']?.toString().toUpperCase() ?? '';

        if (status == 'ISSUED' || status == 'BORROWED') {
          activeBorrowings++;
          
          if (record['due_date'] != null) {
            final dueDate = DateTime.tryParse(record['due_date'].toString());
            if (dueDate != null && dueDate.isBefore(now)) {
              overdueReturns++;
            }
          }
        }
      }

      return {
        'totalBooks': campusBooks.length.toString(),
        'activeBorrowings': activeBorrowings.toString(),
        'overdueReturns': overdueReturns.toString(),
        'totalStudents': campusStudents.length.toString(), // 🚀 Now 100% accurate
      };
    } catch (e) {
      debugPrint("Error loading remote dashboard data: $e");
      throw Exception('Failed to load remote dashboard statistics');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Map<String, dynamic>>(
      future: _dashboardDataFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: Padding(padding: EdgeInsets.all(48.0), child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(_darkGreen))));
        }

        if (snapshot.hasError) {
          return Center(child: Padding(padding: const EdgeInsets.all(48.0), child: Text('Error loading campus data: ${snapshot.error}', style: const TextStyle(color: Colors.redAccent, fontWeight: FontWeight.bold))));
        }

        final data = snapshot.data!;

        return LayoutBuilder(
          builder: (context, constraints) {
            final double availableWidth = constraints.maxWidth - 48.0;
            const double spacing = 16.0;

            int crossAxisCount = 1;
            if (availableWidth >= 1200) {
              crossAxisCount = 4;
            } else if (availableWidth >= 800) {
              crossAxisCount = 2;
            }

            final double cardWidth = ((availableWidth - (spacing * (crossAxisCount - 1))) / crossAxisCount).floorToDouble();

            return SingleChildScrollView(
              padding: const EdgeInsets.all(24.0),
              physics: const BouncingScrollPhysics(),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  
                  // ==========================================
                  // REMOTE CAMPUS CONTEXT BANNER
                  // ==========================================
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.grey.shade200),
                      boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10, offset: const Offset(0, 4))]
                    ),
                    child: Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(color: _standardGold.withOpacity(0.1), shape: BoxShape.circle),
                          child: const Icon(Icons.public_rounded, color: _standardGold, size: 28),
                        ),
                        const SizedBox(width: 20),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'Viewing: ${widget.campusName}',
                                style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: Colors.black87, letterSpacing: 0.5),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                'You are currently browsing the live library network data for this remote campus.',
                                style: TextStyle(fontSize: 14, color: Colors.grey.shade600, fontWeight: FontWeight.w500),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 32),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(width: 4, height: 24, color: _darkGreen),
                          const SizedBox(width: 12),
                          Text(
                            'CAMPUS STATISTICS',
                            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: Colors.grey.shade800, letterSpacing: 1.5),
                          ),
                        ],
                      ),
                      InkWell(
                        onTap: () => setState(() => _showStats = !_showStats),
                        child: Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(border: Border.all(color: _darkGreen, width: 2), color: _showStats ? _darkGreen : Colors.transparent),
                          child: Icon(_showStats ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded, color: _showStats ? Colors.white : _darkGreen, size: 20),
                        ),
                      ),
                    ],
                  ),
                  
                  AnimatedSize(
                    duration: const Duration(milliseconds: 400),
                    curve: Curves.fastOutSlowIn,
                    alignment: Alignment.topCenter,
                    clipBehavior: Clip.hardEdge,
                    child: _showStats 
                      ? Padding(
                          padding: const EdgeInsets.only(top: 24.0),
                          child: SizedBox(
                            width: double.infinity,
                            child: Wrap(
                              spacing: spacing,
                              runSpacing: spacing,
                              children: [
                                SizedBox(
                                  width: cardWidth,
                                  child: _LibraryStatCard(
                                    title: 'Total Campus Books', value: data['totalBooks'], subtitle: 'Books registered here', icon: Icons.menu_book_rounded, iconColor: _darkGreen,
                                  ),
                                ),
                                SizedBox(
                                  width: cardWidth,
                                  child: _LibraryStatCard(
                                    title: 'Active Borrowings', value: data['activeBorrowings'], subtitle: 'Books currently issued out', icon: Icons.sync_alt_rounded, iconColor: _standardGold,
                                  ),
                                ),
                                SizedBox(
                                  width: cardWidth,
                                  child: _LibraryStatCard(
                                    title: 'Overdue Returns', value: data['overdueReturns'], subtitle: 'Action required at campus', icon: Icons.warning_rounded, iconColor: Colors.redAccent, isAlert: (int.tryParse(data['overdueReturns']) ?? 0) > 0,
                                  ),
                                ),
                                SizedBox(
                                  width: cardWidth,
                                  child: _LibraryStatCard(
                                    title: 'Registered Students', value: data['totalStudents'], subtitle: 'Students at this campus', icon: Icons.people_alt_rounded, iconColor: _darkGreen,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      : const SizedBox(width: double.infinity, height: 0.0), 
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}

class _LibraryStatCard extends StatelessWidget {
  final String title;
  final String value;
  final String subtitle;
  final IconData icon;
  final Color iconColor;
  final bool isAlert;

  const _LibraryStatCard({
    required this.title,
    required this.value,
    required this.subtitle,
    required this.icon,
    required this.iconColor,
    this.isAlert = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey.shade200, width: 1),
          right: BorderSide(color: Colors.grey.shade200, width: 1),
          bottom: BorderSide(color: Colors.grey.shade200, width: 1),
          left: BorderSide(color: isAlert ? Colors.redAccent : iconColor, width: 4),
        ),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10, offset: const Offset(0, 4))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: Text(title.toUpperCase(), style: TextStyle(color: Colors.grey.shade500, fontSize: 11, fontWeight: FontWeight.bold, letterSpacing: 1.0), overflow: TextOverflow.ellipsis)),
              Icon(icon, color: iconColor, size: 24),
            ],
          ),
          const SizedBox(height: 16),
          Text(value, style: const TextStyle(fontSize: 32, fontWeight: FontWeight.w900, color: Colors.black87)),
          const SizedBox(height: 4),
          Text(subtitle, style: TextStyle(color: isAlert ? Colors.redAccent : Colors.grey.shade600, fontSize: 12, fontWeight: FontWeight.w500)),
        ],
      ),
    );
  }
}
