// lib/features/admin/tabs/library/library_overview_panel.dart
import 'package:flutter/material.dart';
import '../../../../core/networks/api_client.dart';
import '../../../../core/networks/library_api_service.dart';
import '../../../../core/models/user.dart';

const _green = Color(0xFF026930);
const _gold = Color(0xFFCC7504);
const _ink = Color(0xFF182D26);
const _muted = Color(0xFF6B7D74);
const _line = Color(0xFFE4EBE6);
const _canvas = Color(0xFFF7F8FA);
const _red = Color(0xFFB43E3E);

String _text(dynamic value) {
  if (value is! String && value is! num) return '';
  final result = value.toString().trim();
  return result.toLowerCase() == 'null' ? '' : result;
}
String _field(Map<String, dynamic> row, List<String> keys) {
  for (final key in keys) {
    final value = _text(row[key]);
    if (value.isNotEmpty) return value;
  }
  return '';
}
String _campusKey(String value) => value.toLowerCase().replaceAll(RegExp(r'\s+'), ' ').trim();
DateTime? _date(dynamic value) => DateTime.tryParse(_text(value));
String _dateLabel(DateTime? date) {
  if (date == null) return 'Not recorded';
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return '${date.day} ${months[date.month - 1]} ${date.year}';
}
String _number(int value) => value.toString().replaceAllMapped(
  RegExp(r'(\d)(?=(\d{3})+(?!\d))'), (match) => '${match[1]},',
);
bool _active(Map<String, dynamic> row) =>
    ['ISSUED', 'BORROWED', 'OVERDUE'].contains(_text(row['status']).toUpperCase());
bool _overdue(Map<String, dynamic> row, DateTime now) {
  if (!_active(row)) return false;
  if (_text(row['status']).toUpperCase() == 'OVERDUE') return true;
  final raw = _text(row['due_date']);
  var due = _date(raw);
  if (due == null) return false;
  // A date without a time is due at the end of that calendar day.
  if (RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(raw)) {
    due = DateTime(due.year, due.month, due.day + 1);
  }
  return !now.isBefore(due);
}

class LibraryOverviewPanel extends StatefulWidget {
  final LocalUser? currentUser;
  const LibraryOverviewPanel({super.key, this.currentUser});
  @override
  State<LibraryOverviewPanel> createState() => _LibraryOverviewPanelState();
}

class _LibraryOverviewPanelState extends State<LibraryOverviewPanel> {
  late Future<_OverviewData> _future;
  _OverviewData? _lastData;

  String get _campus => _text(widget.currentUser?.campus);

  @override
  void initState() {
    super.initState();
    _future = _fetch();
    ApiClient.offlineCacheRevision.addListener(_onOfflineCacheChanged);
  }

  void _onOfflineCacheChanged() {
    if (!mounted || _campus.isEmpty) return;
    setState(() {
      _future = _fetch();
    });
  }

  @override
  void dispose() {
    ApiClient.offlineCacheRevision.removeListener(_onOfflineCacheChanged);
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant LibraryOverviewPanel oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.currentUser != widget.currentUser ||
        oldWidget.currentUser?.campus != widget.currentUser?.campus) {
      _lastData = null;
      _future = _fetch();
    }
  }

  Future<_OverviewData> _fetch({bool refresh = false}) async {
    // Capture the scope before asynchronous calls finish.
    final campus = _campusKey(_campus);
    if (campus.isEmpty) return _OverviewData.empty();
    final responses = await Future.wait<dynamic>([
      LibraryApiService.getBooks(refresh: refresh),
      LibraryApiService.getBorrowingRecords(refresh: refresh),
      LibraryApiService.getStudents(refresh: refresh),
    ]);
    List<Map<String, dynamic>> scoped(dynamic response) {
      if (response is! List) throw const FormatException('Expected a list');
      final result = <Map<String, dynamic>>[];
      for (final item in response) {
        if (item is! Map) continue;
        final row = item.map((key, value) => MapEntry(key.toString(), value));
        final value = _field(row, ['campus', 'campus_name', 'campusName', 'branch', 'branch_name']);
        if (_campusKey(value) == campus) result.add(row);
      }
      return result;
    }
    final books = scoped(responses[0]);
    final records = scoped(responses[1]);
    final students = scoped(responses[2]);
    final now = DateTime.now();
    final active = records.where(_active).length;
    final overdue = records.where((row) => _overdue(row, now)).length;
    final unknownDue = records.where((row) => _active(row) &&
        !_overdue(row, now) && _date(row['due_date']) == null).length;
    records.sort((a, b) {
      final ad = _date(a['borrow_date']);
      final bd = _date(b['borrow_date']);
      if (ad == null && bd == null) return 0;
      if (ad == null) return 1;
      if (bd == null) return -1;
      return bd.compareTo(ad);
    });
    final titles = <String, String>{};
    for (final book in books) {
      final id = _field(book, ['id', 'book_id']);
      if (id.isNotEmpty) titles[id] = _field(book, ['title', 'book_title', 'name']);
    }
    final data = _OverviewData(books.length, students.length, active, overdue,
        unknownDue, records.take(5).toList(), titles, now);
    _lastData = data;
    return data;
  }

  Future<void> _refresh() async {
    final next = _fetch(refresh: true);
    setState(() {
      _future = next;
    });
    try { await next; } catch (_) { /* FutureBuilder presents retry state. */ }
  }

  @override
  Widget build(BuildContext context) {
    return ColoredBox(
      color: _canvas,
      child: LayoutBuilder(builder: (context, constraints) {
        final width = constraints.hasBoundedWidth ? constraints.maxWidth : MediaQuery.of(context).size.width;
        final padding = width < 600 ? 16.0 : 24.0;
        return FutureBuilder<_OverviewData>(
          future: _future,
          builder: (context, snapshot) {
            final loading = snapshot.connectionState != ConnectionState.done;
            final data = snapshot.data ?? _lastData;
            return RefreshIndicator(
              color: _green,
              onRefresh: _refresh,
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: EdgeInsets.all(padding),
                child: Center(child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 1440),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
                    _header(loading),
                    const SizedBox(height: 24),
                    if (_campus.isEmpty)
                      _message(Icons.location_city_outlined, 'Choose a campus to get started',
                          'Assign a campus to your staff profile to view its library overview.')
                    else if (loading && data == null)
                      _loading()
                    else if (data == null)
                      _message(Icons.cloud_off_rounded, 'Unable to load the overview',
                          'Check your connection and library service, then try again.', retry: true)
                    else ...[
                      LayoutBuilder(builder: (context, c) {
                        final columns = c.maxWidth >= 860 ? 4 : c.maxWidth >= 440 ? 2 : 1;
                        final cardWidth = (c.maxWidth - 12 * (columns - 1)) / columns;
                        return Wrap(spacing: 12, runSpacing: 12, children: [
                          _stat(cardWidth, 'Book titles', data.books, 'Campus catalogue', Icons.menu_book_outlined, _green),
                          _stat(cardWidth, 'Active loans', data.active, 'Awaiting return', Icons.swap_horiz_rounded, _green),
                          _stat(cardWidth, 'Overdue', data.overdue, 'Loans past due', Icons.schedule_outlined, data.overdue > 0 ? _red : _green),
                          _stat(cardWidth, 'Students', data.students, 'Library registrations', Icons.people_outline, _green),
                        ]);
                      }),
                      const SizedBox(height: 20),
                      _recent(data),
                      const SizedBox(height: 12),
                      _circulation(data),
                      const SizedBox(height: 16),
                      Text('Campus: $_campus  ·  Updated ${_dateLabel(data.updated)} at ${TimeOfDay.fromDateTime(data.updated).format(context)}',
                        style: const TextStyle(fontSize: 12, color: _muted)),
                    ],
                  ]),
                )),
              ),
            );
          },
        );
      }),
    );
  }

  Widget _header(bool loading) {
    final title = Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      const Text('Library overview', style: TextStyle(color: _ink,
          fontSize: 22, fontWeight: FontWeight.w700, letterSpacing: -0.5)),
      const SizedBox(height: 5),
      Text(_campus.isEmpty ? 'Campus not assigned' : _campus,
          style: const TextStyle(color: _muted, fontSize: 12)),
    ]);
    final controls = Wrap(spacing: 10, runSpacing: 8,
        crossAxisAlignment: WrapCrossAlignment.center, children: [
      OutlinedButton.icon(
        onPressed: loading || _campus.isEmpty ? null : () { _refresh(); },
        icon: Icon(loading ? Icons.hourglass_top_rounded : Icons.refresh, size: 16),
        label: Text(loading ? 'Loading' : 'Refresh'),
        style: OutlinedButton.styleFrom(
          foregroundColor: _ink, backgroundColor: Colors.white,
          side: const BorderSide(color: _line),
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
        ),
      ),
    ]);
    return LayoutBuilder(builder: (context, c) => c.maxWidth < 420
        ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            title, const SizedBox(height: 12), controls,
          ])
        : Row(children: [Expanded(child: title), const SizedBox(width: 16), controls]));
  }

  Widget _section(String title, String subtitle, {Widget? action}) => Row(children: [
    Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(title, style: const TextStyle(color: _ink, fontSize: 15, fontWeight: FontWeight.w700)),
      const SizedBox(height: 5),
      Text(subtitle, style: const TextStyle(color: _muted, fontSize: 12, height: 1.5)),
    ])),
    if (action != null) action,
  ]);

  Widget _surface(Widget child, {EdgeInsets padding = const EdgeInsets.all(18)}) => Container(
    width: double.infinity, padding: padding,
    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8), border: Border.all(color: _line)),
    child: child,
  );

  Widget _stat(double width, String title, int value, String caption, IconData icon, Color color) => SizedBox(
    width: width,
    child: _surface(Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Row(children: [
        Expanded(child: Text(title, style: const TextStyle(fontSize: 12,
            fontWeight: FontWeight.w500, color: _muted))),
        Icon(icon, size: 18, color: color),
      ]),
      const SizedBox(height: 12),
      Text(_number(value), style: TextStyle(fontSize: 28, height: 1.2,
          fontWeight: FontWeight.w700, color: color == _red ? _red : _ink)),
      const SizedBox(height: 7),
      Text(caption, style: const TextStyle(color: _muted, fontSize: 11)),
    ])),
  );

  Widget _circulation(_OverviewData data) => Padding(
    padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 4),
    child: Wrap(spacing: 22, runSpacing: 10, children: [
      _statusCount('Within due date', data.active - data.overdue - data.unknownDue, _green),
      _statusCount('Overdue', data.overdue, data.overdue > 0 ? _red : _muted),
      if (data.unknownDue > 0) _statusCount('Missing due date', data.unknownDue, _gold),
    ]),
  );

  Widget _statusCount(String label, int value, Color color) => Row(
    mainAxisSize: MainAxisSize.min, children: [
      Container(width: 6, height: 6, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
      const SizedBox(width: 7),
      Text('$label: ${_number(value)}', style: const TextStyle(fontSize: 12, color: _muted)),
    ],
  );

  Widget _recent(_OverviewData data) => Container(
    clipBehavior: Clip.antiAlias,
    decoration: BoxDecoration(color: Colors.white,
        border: Border.all(color: _line), borderRadius: BorderRadius.circular(8)),
    child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      Padding(padding: const EdgeInsets.all(18),
        child: _section('Recent borrowing', 'Latest five records by borrow date')),
      const Divider(height: 1, color: _line),
      if (data.recent.isEmpty)
        const Padding(padding: EdgeInsets.all(32), child: Text(
          'No borrowing records for this campus yet.',
          style: TextStyle(color: _muted, fontSize: 13)))
      else LayoutBuilder(builder: (context, c) {
        // Mobile and enlarged text use stacked rows; desktop uses aligned columns.
        if (c.maxWidth < 760 || MediaQuery.textScalerOf(context).scale(13) > 18) {
          return Padding(padding: const EdgeInsets.all(18), child: Column(children: [
            for (var i = 0; i < data.recent.length; i++) ...[
              if (i > 0) const Divider(height: 28, color: _line),
              _loanRow(data.recent[i], data),
            ],
          ]));
        }
        return Table(
          columnWidths: const {
            0: FlexColumnWidth(3), 1: FlexColumnWidth(1.7),
            2: FlexColumnWidth(1.5), 3: FlexColumnWidth(1.5),
            4: FlexColumnWidth(1.2),
          },
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            TableRow(decoration: const BoxDecoration(color: Color(0xFFF8FAF9)), children: [
              for (final label in ['BOOK / REFERENCE', 'STUDENT', 'BORROWED', 'DUE DATE', 'STATUS'])
                Padding(padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
                  child: Text(label, style: const TextStyle(color: _muted,
                      fontSize: 10, fontWeight: FontWeight.w600, letterSpacing: 0.5))),
            ]),
            for (final row in data.recent) _tableRow(row, data),
          ],
        );
      }),
    ]),
  );

  TableRow _tableRow(Map<String, dynamic> row, _OverviewData data) {
    final id = _text(row['book_id']);
    final suppliedTitle = _field(row, ['book_title', 'title']);
    final title = suppliedTitle.isNotEmpty ? suppliedTitle : _text(data.titles[id]);
    final reference = _field(row, ['ref_no']);
    final status = _text(row['status']).toUpperCase();
    final overdue = _overdue(row, data.updated);
    final returned = status == 'RETURNED';
    final label = overdue ? 'Overdue' : returned ? 'Returned'
        : _active(row) ? 'On loan' : status.isEmpty ? 'Unknown' : _text(row['status']);
    final color = overdue ? _red : returned ? _green : _active(row) ? _gold : _muted;
    Widget cell(Widget child) => Padding(
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 17), child: child);
    Widget text(String value, {Color color = _ink}) => Text(value,
        style: TextStyle(fontSize: 12, color: color, height: 1.5));
    return TableRow(decoration: const BoxDecoration(
      border: Border(top: BorderSide(color: _line))), children: [
      cell(Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(title.isNotEmpty ? title : id.isEmpty ? 'Book not recorded' : 'Book $id',
          style: const TextStyle(color: _ink, fontSize: 13, fontWeight: FontWeight.w600)),
        if (reference.isNotEmpty || id.isNotEmpty) ...[
          const SizedBox(height: 4),
          text(reference.isNotEmpty ? reference : id, color: _muted),
        ],
      ])),
      cell(text(_text(row['student_id']).isEmpty ? 'Not recorded' : _text(row['student_id']))),
      cell(text(_dateLabel(_date(row['borrow_date'])), color: _muted)),
      cell(text(_dateLabel(_date(row['due_date'])), color: overdue ? _red : _muted)),
      cell(Align(alignment: Alignment.centerLeft, child: _badge(label, color.withOpacity(0.07), color))),
    ]);
  }

  Widget _loanRow(Map<String, dynamic> row, _OverviewData data) {
    final bookId = _text(row['book_id']);
    final title = _field(row, ['book_title', 'title']);
    final bookTitle = title.isNotEmpty ? title : _text(data.titles[bookId]);
    final status = _text(row['status']).toUpperCase();
    final overdue = _overdue(row, data.updated);
    final returned = status == 'RETURNED';
    final label = overdue ? 'Overdue' : returned ? 'Returned' : _active(row) ? 'On loan' : status.isEmpty ? 'Unknown' : _text(row['status']);
    final color = overdue ? _red : returned ? _green : _active(row) ? _gold : _muted;
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: _canvas, borderRadius: BorderRadius.circular(10)),
        child: const Icon(Icons.book_outlined, color: _green, size: 20)),
      const SizedBox(width: 12),
      Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(bookTitle.isNotEmpty ? bookTitle : bookId.isEmpty ? 'Book not recorded' : 'Book $bookId',
          style: const TextStyle(color: _ink, fontSize: 14, fontWeight: FontWeight.w600)),
        const SizedBox(height: 5),
        Text('Student: ${_text(row['student_id']).isEmpty ? 'Not recorded' : _text(row['student_id'])}', style: const TextStyle(fontSize: 12, color: _muted)),
        const SizedBox(height: 8),
        Wrap(spacing: 10, runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [
          _badge(label, color.withOpacity(0.08), color),
          Text('Borrowed ${_dateLabel(_date(row['borrow_date']))}', style: const TextStyle(fontSize: 11, color: _muted)),
          Text('Due ${_dateLabel(_date(row['due_date']))}', style: const TextStyle(fontSize: 11, color: _muted)),
        ]),
      ])),
    ]);
  }

  Widget _badge(String text, Color background, Color foreground) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
    decoration: BoxDecoration(color: background, borderRadius: BorderRadius.circular(7)),
    child: Text(text, style: TextStyle(color: foreground, fontSize: 11, fontWeight: FontWeight.w600)),
  );

  Widget _loading() => _surface(const Padding(
    padding: EdgeInsets.symmetric(vertical: 48),
    child: Column(children: [
      SizedBox(width: 26, height: 26, child: CircularProgressIndicator(strokeWidth: 2.5, color: _green)),
      SizedBox(height: 16),
      Text('Loading campus overview…', style: TextStyle(color: _muted, fontSize: 13)),
    ]),
  ));

  Widget _message(IconData icon, String title, String message, {bool retry = false}) => _surface(
    Padding(padding: const EdgeInsets.symmetric(vertical: 28), child: Column(children: [
      Icon(icon, color: _green, size: 34),
      const SizedBox(height: 14),
      Text(title, textAlign: TextAlign.center, style: const TextStyle(color: _ink, fontSize: 15, fontWeight: FontWeight.w700)),
      const SizedBox(height: 8),
      Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted, fontSize: 13, height: 1.6)),
      if (retry) ...[const SizedBox(height: 18), OutlinedButton.icon(
        onPressed: () { _refresh(); }, icon: const Icon(Icons.refresh), label: const Text('Try again'),
        style: OutlinedButton.styleFrom(foregroundColor: _green),
      )],
    ])),
  );
}

class _OverviewData {
  final int books, students, active, overdue, unknownDue;
  final List<Map<String, dynamic>> recent;
  final Map<String, String> titles;
  final DateTime updated;
  const _OverviewData(this.books, this.students, this.active, this.overdue,
      this.unknownDue, this.recent, this.titles, this.updated);
  factory _OverviewData.empty() => _OverviewData(0, 0, 0, 0, 0, [], {}, DateTime.now());
}
