import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../../../core/constants/app_colors.dart';
import '../../../core/networks/api_client.dart';
import '../../../core/networks/library_api_service.dart';
import '../../../core/services/leave_service.dart';
import '../../../core/services/database_service.dart';

/// University-wide administration overview. Keep this widget inside the
/// dashboard's normal content panel.
class AdminHomeFeedTab extends StatefulWidget {
  const AdminHomeFeedTab({super.key});

  @override
  State<AdminHomeFeedTab> createState() => _AdminHomeFeedTabState();
}

class _AdminHomeFeedTabState extends State<AdminHomeFeedTab> {
  static const Color _standardGold = Color(0xFFFFD700);
  static const Color _darkGreen = AppColors.brandGreen;

  bool _isLoading = true;
  bool _showingSavedCopy = false;
  int? _totalUsers;
  int? _pendingLeaveActions;
  int? _totalStaff;
  int? _totalAdmins;
  int? _newsCount;
  int? _totalCampuses;
  int? _totalGlobalBooks;
  int? _totalGlobalBorrowings;
  int? _totalGlobalStudents;

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

  Future<void> _loadSavedCopyThenRefresh() async {
    final prefs = await SharedPreferences.getInstance();
    final user = await DatabaseService.getLocalUser();
    final email = user?.email.trim().toLowerCase() ?? '';
    final cacheKey = email.isEmpty
        ? ''
        : 'rockview_admin_home_metrics_v2_${base64Url.encode(utf8.encode(email))}';
    final saved = email.isEmpty ? null : prefs.getString(cacheKey);
    if (saved != null) {
      try {
        final decoded = json.decode(saved);
        if (decoded is Map) {
          _applyMetrics(decoded);
          if (mounted) {
            setState(() {
              _isLoading = false;
              _showingSavedCopy = true;
            });
          }
        }
      } catch (_) {
        // Ignore a damaged local cache and load from the server instead.
      }
    }
    await _fetchLiveMetrics(prefs: prefs, cacheKey: cacheKey);
  }

  Future<void> _fetchLiveMetrics({SharedPreferences? prefs, required String cacheKey}) async {
    final local = prefs ?? await SharedPreferences.getInstance();
    if (!_hasAnyMetric && mounted) setState(() => _isLoading = true);

    try {
      // These are the routes used by ApiClient in this project.
      final headers = await ApiClient.getHeaders();
      final results = await Future.wait<dynamic>([
        _getRows('/api/users.php?role=staff', headers),
        _getRows('/api/admin.php/admins', headers),
        _safeValue(ApiClient.getPosts(limit: 100, page: 1)),
        _getRows('/api/campuses.php', headers),
        _safeValue(LeaveService.list(scope: 'action')),
        _safeValue(LibraryApiService.getBooks()),
        _safeValue(LibraryApiService.getBorrowingRecords()),
        _safeValue(LibraryApiService.getStudents()),
      ]);
      if (!mounted) return;

      final staff = results[0] as List<Map<String, dynamic>>?;
      final admins = results[1] as List<Map<String, dynamic>>?;
      final news = results[2] == null ? null : _mapRows(results[2]);
      final campuses = results[3] as List<Map<String, dynamic>>?;
      final leave = results[4];
      final books = results[5] == null ? null : _mapRows(results[5]);
      final borrowings = results[6] == null ? null : _mapRows(results[6]);
      final libraryStudents = results[7] == null ? null : _mapRows(results[7]);

      setState(() {
        if (staff != null) _totalStaff = staff.length;
        if (admins != null) _totalAdmins = admins.length;
        // The university user total is the sum of staff and administrators.
        if (staff != null && admins != null) {
          _totalUsers = staff.length + admins.length;
        }
        if (leave is Map) _pendingLeaveActions = _leaveActionCount(leave);
        if (news != null) _newsCount = news.length;
        if (campuses != null) _totalCampuses = campuses.length;
        if (books != null) _totalGlobalBooks = _bookCopyCount(books);
        if (borrowings != null) {
          _totalGlobalBorrowings = borrowings.where(_isOpenBorrowing).length;
        }
        if (libraryStudents != null) _totalGlobalStudents = libraryStudents.length;
        _isLoading = false;
        _showingSavedCopy = staff == null || admins == null || news == null ||
            campuses == null || leave == null || books == null ||
            borrowings == null || libraryStudents == null;
      });

      if (_hasAnyMetric) {
        if (cacheKey.isNotEmpty) {
          await local.setString(cacheKey, json.encode(_metricsAsMap()));
        }
      }
    } catch (_) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _showingSavedCopy = _hasAnyMetric;
        });
      }
    }
  }

  bool get _hasAnyMetric => [
        _totalUsers,
        _pendingLeaveActions,
        _totalStaff,
        _totalAdmins,
        _newsCount,
        _totalCampuses,
        _totalGlobalBooks,
        _totalGlobalBorrowings,
        _totalGlobalStudents,
      ].any((value) => value != null);

  Future<dynamic> _safeValue(Future<dynamic> request) async {
    try {
      return await request;
    } catch (_) {
      return null;
    }
  }

  Future<List<Map<String, dynamic>>?> _getRows(
    String path,
    Map<String, String> headers,
  ) async {
    final base = ApiClient.baseUrl.replaceFirst(RegExp(r'/+$'), '');
    try {
      final response = await ApiClient.offlineFirstGet(
              Uri.parse('$base$path'), headers: headers)
          .timeout(const Duration(seconds: 15));
      return _responseRows(response);
    } catch (_) {
      // Use the saved local copy when the live API is unreachable.
      return null;
    }
  }

  List<Map<String, dynamic>>? _responseRows(http.Response response) {
    if (response.statusCode < 200 || response.statusCode >= 300) return null;
    try {
      dynamic value = json.decode(response.body);
      for (var depth = 0; depth < 5; depth++) {
        if (value is List) return _mapRows(value);
        if (value is! Map) return null;
        dynamic next;
        for (final key in [
          'data', 'users', 'staff', 'admins', 'posts', 'campuses', 'items',
          'records', 'results',
        ]) {
          if (value.containsKey(key)) {
            next = value[key];
            break;
          }
        }
        if (next == null) return null;
        value = next;
      }
    } catch (_) {}
    return null;
  }

  List<Map<String, dynamic>> _mapRows(dynamic value) {
    if (value is! List) return [];
    return value
        .whereType<Map>()
        .map((row) => row.map((key, value) => MapEntry(key.toString(), value)))
        .toList();
  }

  bool _isOpenBorrowing(Map<String, dynamic> borrowing) {
    final status = (borrowing['status'] ?? borrowing['state'] ?? 'active')
        .toString()
        .trim()
        .toLowerCase();
    return !{'returned', 'cancelled', 'canceled', 'rejected'}.contains(status);
  }

  int _bookCopyCount(List<Map<String, dynamic>> books) {
    var count = 0;
    for (final book in books) {
      final copies = int.tryParse(
        '${book['total_copies'] ?? book['copies'] ?? ''}',
      );
      count += copies == null ? 1 : (copies < 0 ? 0 : copies);
    }
    return count;
  }

  int? _leaveActionCount(Map leave) {
    final count = int.tryParse('${leave['action_required_count'] ?? ''}');
    if (count != null) return count;
    final rows = leave['data'];
    if (rows is List) return rows.length;
    return null;
  }

  Map<String, dynamic> _metricsAsMap() => {
        'totalUsers': _totalUsers,
        'pendingLeaveActions': _pendingLeaveActions,
        'totalStaff': _totalStaff,
        'totalAdmins': _totalAdmins,
        'totalNews': _newsCount,
        'totalCampuses': _totalCampuses,
        'totalGlobalBooks': _totalGlobalBooks,
        'totalGlobalBorrowings': _totalGlobalBorrowings,
        'totalGlobalStudents': _totalGlobalStudents,
      };

  void _applyMetrics(Map data) {
    int? number(String key) => int.tryParse('${data[key] ?? ''}');
    _totalUsers = number('totalUsers');
    _pendingLeaveActions = number('pendingLeaveActions');
    _totalStaff = number('totalStaff');
    _totalAdmins = number('totalAdmins');
    _newsCount = number('totalNews') ?? number('activePosts');
    _totalCampuses = number('totalCampuses');
    _totalGlobalBooks = number('totalGlobalBooks');
    _totalGlobalBorrowings = number('totalGlobalBorrowings');
    _totalGlobalStudents = number('totalGlobalStudents');
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(32),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Admin Dashboard',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w900,
                  color: _standardGold,
                  letterSpacing: -0.5,
                ),
              ),
              IconButton(
                icon: const Icon(Icons.refresh_rounded, color: _darkGreen),
                onPressed: () => _loadSavedCopyThenRefresh(),
                tooltip: 'Refresh Metrics', 
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            'University-wide system overview and recent activities.',
            style: TextStyle(fontSize: 15, color: Colors.grey.shade600),
          ),
          if (_showingSavedCopy) ...[
            const SizedBox(height: 8),
            Row(children: [
              const Icon(Icons.cloud_off_rounded, size: 16, color: _darkGreen),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  'Showing saved dashboard figures where a live update is unavailable.',
                  style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                ),
              ),
            ]),
          ],
          const SizedBox(height: 32),
          _buildMetricsCard(
            isLoading: _isLoading,
            metrics: [
              _Metric('Total Users', _display(_totalUsers), Icons.people_alt_rounded),
              _Metric('Pending Leave Actions', _display(_pendingLeaveActions), Icons.pending_actions_rounded),
              _Metric('Staff Members', _display(_totalStaff), Icons.badge_rounded),
              _Metric('Administrators', _display(_totalAdmins), Icons.admin_panel_settings),
              _Metric('Campuses', _display(_totalCampuses), Icons.domain_rounded),
              _Metric('News', _display(_newsCount), Icons.newspaper_rounded),
            ],
          ),
          if (!_isLoading) ...[
            const SizedBox(height: 24),
            _buildMetricsCard(
              isLoading: false,
              metrics: [
                _Metric('Total Book Copies', _display(_totalGlobalBooks), Icons.library_books_rounded),
                _Metric('Active Borrowings', _display(_totalGlobalBorrowings), Icons.sync_alt_rounded),
                _Metric('Library Students', _display(_totalGlobalStudents), Icons.school_rounded),
              ],
            ),
          ],
        ],
      ),
    );
  }

  String _display(int? value) => value?.toString() ?? '—';

  Widget _buildMetricsCard({
    required bool isLoading,
    required List<_Metric> metrics,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey.shade300, width: 1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: isLoading
          ? const Padding(
              padding: EdgeInsets.all(40),
              child: Center(child: CircularProgressIndicator(color: _darkGreen)),
            )
          : LayoutBuilder(
              builder: (context, constraints) {
                final columns = constraints.maxWidth >= 640 ? 3 : 1;
                final rows = <Widget>[];
                for (var start = 0; start < metrics.length; start += columns) {
                  final end = start + columns > metrics.length
                      ? metrics.length
                      : start + columns;
                  final batch = metrics.sublist(start, end);
                  if (rows.isNotEmpty) {
                    rows.add(const Divider(height: 1, thickness: 1));
                  }
                  rows.add(
                    IntrinsicHeight(
                      child: Row(
                        children: [
                          for (var i = 0; i < batch.length; i++) ...[
                            if (i > 0) _buildVerticalDivider(),
                            Expanded(child: _buildFlatMetricItem(batch[i])),
                          ],
                        ],
                      ),
                    ),
                  );
                }
                return Column(children: rows);
              },
            ),
    );
  }

  Widget _buildVerticalDivider() => Container(
        width: 1,
        color: Colors.grey.shade300,
      );

  Widget _buildFlatMetricItem(_Metric metric) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
      color: Colors.transparent,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  metric.title.toUpperCase(),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey.shade600,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Icon(metric.icon, size: 20, color: _standardGold),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            metric.value,
            style: const TextStyle(
              fontSize: 36,
              fontWeight: FontWeight.w900,
              color: Colors.black87,
              letterSpacing: -1,
            ),
          ),
        ],
      ),
    );
  }
}

class _Metric {
  final String title;
  final String value;
  final IconData icon;

  const _Metric(this.title, this.value, this.icon);
}
