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

import 'package:flutter/material.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 AssignBookDialog extends StatefulWidget {
  final Map<String, dynamic> book;

  const AssignBookDialog({super.key, required this.book});

  @override
  State<AssignBookDialog> createState() => _AssignBookDialogState();
}

class _AssignBookDialogState extends State<AssignBookDialog> {
  final _formKey = GlobalKey<FormState>();

  final _studentIdController = TextEditingController();
  final _studentNameController = TextEditingController();
  final _departmentController = TextEditingController();
  final _campusController = TextEditingController();
  final _bookIdController = TextEditingController();

  bool _isSubmitting = false;
  bool _isLoadingStudents = true;
  bool _hasSearchedAndFailed = false;

  List<dynamic> _allStudents = [];
  Map<String, dynamic>? _verifiedStudent;
  LocalUser? _currentUser;

  late DateTime _borrowDate;
  late DateTime _dueDate;

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

    _borrowDate = DateTime.now();
    _dueDate = _borrowDate.add(const Duration(days: 7));

    _bookIdController.text = _readValue(widget.book, ['id', 'book_id', 'accession_no', 'accession_number']);

    _initializeData();
  }

  @override
  void dispose() {
    _studentIdController.dispose();
    _studentNameController.dispose();
    _departmentController.dispose();
    _campusController.dispose();
    _bookIdController.dispose();
    super.dispose();
  }

  // ============================================================
  // INITIAL DATA
  // ============================================================

  Future<LocalUser?> _loadCurrentUser() async {
    try {
      return await DatabaseService.getLocalUser();
    } catch (_) {
      // A local profile failure must not discard the student directory.
      return null;
    }
  }

  Future<void> _initializeData() async {
    try {
      final results = await Future.wait<dynamic>([
        _loadCurrentUser(),
        LibraryApiService.getStudents(),
      ]);

      final LocalUser? currentUser = results[0] as LocalUser?;
      final List<dynamic> students = results[1] as List<dynamic>;

      if (!mounted) return;

      setState(() {
        _currentUser = currentUser;
        _allStudents = students;
        _isLoadingStudents = false;
        _campusController.text = _resolveCampus();
      });


      debugPrint('LIBRARY STUDENTS LOADED: ${students.length}');
    } catch (e, stackTrace) {
      debugPrint('LIBRARY INITIALIZATION ERROR: $e');
      debugPrintStack(stackTrace: stackTrace);

      if (!mounted) return;

      setState(() => _isLoadingStudents = false);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Unable to load library information: $e'), backgroundColor: Colors.redAccent, behavior: SnackBarBehavior.floating),
      );
    }
  }

  // ============================================================
  // HELPERS
  // ============================================================

  Map<String, dynamic>? _asMap(dynamic value) {
    if (value is Map<String, dynamic>) return value;
    if (value is Map) return value.map((key, value) => MapEntry(key.toString(), value));
    return null;
  }

  String _readValue(Map<String, dynamic>? data, List<String> keys) {
    if (data == null) return '';

    for (final key in keys) {
      final value = data[key];

      if (value is String || value is num) {
        final text = value.toString().trim();
        if (text.isNotEmpty && text.toLowerCase() != 'null') return text;
      }
    }

    return '';
  }

  // ============================================================
  // CAMPUS
  // ============================================================

  String _resolveCampus() {
    // 1. Logged-in librarian/admin campus
    final adminCampus = _readValue({'campus': _currentUser?.campus}, ['campus']);
    if (adminCampus.isNotEmpty) return adminCampus;

    // 2. Book campus
    final bookCampus = _readValue(widget.book, ['campus', 'campus_name', 'campusName', 'branch', 'branch_name']);
    if (bookCampus.isNotEmpty) return bookCampus;

    // 3. Student campus
    final studentCampus = _readValue(_verifiedStudent, ['campus', 'campus_name', 'campusName', 'branch', 'branch_name']);
    if (studentCampus.isNotEmpty) return studentCampus;

    return '';
  }

  // ============================================================
  // STUDENT SEARCH
  // ============================================================

  void _onStudentIdChanged(String value) {
    final query = value.trim().toLowerCase();

    if (query.isEmpty) {
      setState(() {
        _verifiedStudent = null;
        _hasSearchedAndFailed = false;
        _studentNameController.clear();
        _departmentController.clear();
        _campusController.text = _resolveCampus();
      });

      return;
    }

    Map<String, dynamic>? foundStudent;

    for (final rawStudent in _allStudents) {
      final student = _asMap(rawStudent);
      if (student == null) continue;

      const idKeys = ['id', 'student_id', 'student_no', 'student_number', 'registration_number', 'reg_no'];
      final matches = idKeys.any(
        (key) => _readValue(student, [key]).toLowerCase() == query,
      );
      if (matches) {
        // Never silently select one of two students with the same identifier.
        if (foundStudent != null) {
          foundStudent = null;
          break;
        }
        foundStudent = student;
      }
    }

    setState(() {
      if (foundStudent != null) {
        _verifiedStudent = foundStudent;
        _hasSearchedAndFailed = false;

        final studentName = _readValue(foundStudent, ['name', 'student_name', 'full_name']);
        final department = _readValue(foundStudent, ['department', 'department_name', 'programme', 'program']);

        _studentNameController.text = studentName.isNotEmpty ? studentName : 'Unknown Name';
        _departmentController.text = department.isNotEmpty ? department : 'Unassigned Department';

        // IMPORTANT: campus is retrieved and displayed here.
        _campusController.text = _resolveCampus();
      } else {
        _verifiedStudent = null;
        _hasSearchedAndFailed = true;

        _studentNameController.clear();
        _departmentController.clear();

        // Keep admin/book campus even if student search fails.
        _campusController.text = _resolveCampus();
      }
    });
  }

  // ============================================================
  // DATES
  // ============================================================

  String _formatDate(DateTime date) {
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return '${months[date.month - 1]} ${date.day.toString().padLeft(2, '0')}, ${date.year}';
  }

  int get _daysRemaining {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final due = DateTime(_dueDate.year, _dueDate.month, _dueDate.day);
    return due.difference(today).inDays;
  }

  Future<void> _selectBorrowDate(BuildContext context) async {
    final now = DateTime.now();

    final picked = await showDatePicker(
      context: context,
      initialDate: DateTime(_borrowDate.year, _borrowDate.month, _borrowDate.day),
      firstDate: DateTime(2020),
      lastDate: DateTime(now.year, now.month, now.day),
      builder: (context, child) => Theme(
        data: Theme.of(context).copyWith(colorScheme: const ColorScheme.light(primary: _darkGreen, onPrimary: Colors.white, onSurface: Colors.black)),
        child: child!,
      ),
    );

    if (picked == null || !mounted) return;

    setState(() {
      // Preserve time while changing only the date.
      _borrowDate = DateTime(picked.year, picked.month, picked.day, _borrowDate.hour, _borrowDate.minute, _borrowDate.second);
      _dueDate = _borrowDate.add(const Duration(days: 7));
    });
  }

  // ============================================================
  // ISSUE BOOK
  // ============================================================

  Future<void> _submitAssignment() async {
    if (_isSubmitting || _isLoadingStudents) return;
    final resolvedCampus = _resolveCampus();
    if (resolvedCampus.isNotEmpty) _campusController.text = resolvedCampus;
    if (_verifiedStudent == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please enter and verify a valid student number.'), backgroundColor: Colors.redAccent, behavior: SnackBarBehavior.floating),
      );
      return;
    }

    if (!(_formKey.currentState?.validate() ?? false) || _isSubmitting) return;

    setState(() => _isSubmitting = true);

    try {
      final studentId = _readValue(_verifiedStudent, ['id', 'student_id', 'student_no', 'student_number', 'registration_number', 'reg_no']);
      final studentName = _readValue(_verifiedStudent, ['name', 'student_name', 'full_name']);
      final bookId = _readValue(widget.book, ['id', 'book_id', 'accession_no', 'accession_number']);
      final campus = _readValue({'campus': _campusController.text}, ['campus']);

      if (studentId.isEmpty) throw Exception('Student ID could not be determined.');
      if (bookId.isEmpty) throw Exception('Book ID could not be determined.');
      if (campus.isEmpty) throw Exception('Campus could not be determined for this borrowing transaction.');

      // ==========================================================
      // ONLY COLUMNS THAT EXIST IN borrow_records ARE SENT
      // ref_no is generated by PHP, therefore Flutter does not send it.
      // ==========================================================

      final Map<String, dynamic> borrowingRecordData = {
        'student_id': studentId,
        'book_id': bookId,
        'borrow_date': _borrowDate.toIso8601String(),
        'due_date': _dueDate.toIso8601String(),
        'status': 'Borrowed',
        'remarks': studentName.isNotEmpty ? 'Issued to $studentName ($studentId)' : 'Issued to $studentId',
        'campus': campus,
      };

      await LibraryApiService.issueBook(borrowingRecordData);

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(studentName.isNotEmpty ? 'Book successfully issued to $studentName.' : 'Book successfully issued to $studentId.'),
          backgroundColor: _darkGreen,
          behavior: SnackBarBehavior.floating,
          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        ),
      );

      Navigator.of(context).pop(true);
    } catch (e, stackTrace) {
      debugPrint('BOOK ISSUANCE FAILED: $e');
      debugPrintStack(stackTrace: stackTrace);

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Issuance Failed: $e'), backgroundColor: Colors.redAccent, behavior: SnackBarBehavior.floating, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero)),
      );
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  // ============================================================
  // INPUT DESIGN
  // ============================================================

  InputDecoration _inputDecoration({required String hint, required IconData icon, Widget? suffix}) {
    return InputDecoration(
      hintText: hint,
      hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14),
      prefixIcon: Icon(icon, color: Colors.grey.shade400, size: 22),
      suffixIcon: suffix,
      filled: true,
      fillColor: Colors.white,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18),
      border: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _hasSearchedAndFailed ? Colors.redAccent : _darkGreen, width: 1.5)),
      errorBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.redAccent)),
      focusedErrorBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.redAccent, width: 1.5)),
    );
  }

  Widget _dateBox(String label, DateTime date, {VoidCallback? onTap}) {
    return Expanded(
      child: InkWell(
        onTap: _isSubmitting ? null : onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          decoration: BoxDecoration(color: onTap != null ? Colors.grey.shade50 : Colors.white, border: Border.all(color: Colors.grey.shade300)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(label, style: TextStyle(fontSize: 11, color: Colors.grey.shade500)),
                  const SizedBox(height: 4),
                  Text(_formatDate(date), style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Colors.black87)),
                ],
              ),
              Icon(onTap != null ? Icons.edit_calendar : Icons.calendar_today, color: onTap != null ? _darkGreen : Colors.grey.shade400, size: 20),
            ],
          ),
        ),
      ),
    );
  }

  // ============================================================
  // USER INTERFACE
  // ============================================================

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      backgroundColor: Colors.white,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 560, maxHeight: MediaQuery.of(context).size.height * 0.92),
        child: Container(
          decoration: BoxDecoration(color: Colors.white, border: Border.all(color: Colors.grey.shade300)),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [

              // HEADER
              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('ISSUE BOOK (BORROWING RECORD)', style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold, letterSpacing: 1)),
                    IconButton(onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(false), icon: const Icon(Icons.close_rounded, color: Colors.white, size: 20), padding: EdgeInsets.zero, constraints: const BoxConstraints()),
                  ],
                ),
              ),

              // FORM
              Flexible(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(28),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: [

                        TextFormField(
                          controller: _studentIdController,
                          enabled: !_isSubmitting && !_isLoadingStudents,
                          onChanged: _onStudentIdChanged,
                          cursorColor: _darkGreen,
                          validator: (value) {
                            if (value == null || value.trim().isEmpty) return 'Student number is required.';
                            if (_verifiedStudent == null) return 'Student could not be verified.';
                            return null;
                          },
                          decoration: _inputDecoration(
                            hint: 'Student Number',
                            icon: Icons.assignment_ind_outlined,
                            suffix: _isLoadingStudents
                                ? const Padding(padding: EdgeInsets.all(14), child: SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)))
                                : _verifiedStudent != null
                                    ? const Icon(Icons.check_circle, color: Colors.green, size: 20)
                                    : _hasSearchedAndFailed
                                        ? const Icon(Icons.cancel, color: Colors.redAccent, size: 20)
                                        : null,
                          ),
                        ),

                        const SizedBox(height: 14),

                        TextFormField(
                          controller: _studentNameController,
                          readOnly: true,
                          decoration: _inputDecoration(hint: 'Student Name', icon: Icons.person_outline),
                        ),

                        const SizedBox(height: 14),

                        TextFormField(
                          controller: _departmentController,
                          readOnly: true,
                          decoration: _inputDecoration(hint: 'Student Department', icon: Icons.account_tree_outlined),
                        ),

                        const SizedBox(height: 14),

                        // Use the existing campus; allow entry only when no source supplies one.
                        TextFormField(
                          controller: _campusController,
                          enabled: !_isSubmitting && !_isLoadingStudents,
                          readOnly: _resolveCampus().isNotEmpty,
                          validator: (value) => _readValue({'campus': value}, ['campus']).isEmpty
                              ? 'Enter the correct issuing campus.' : null,
                          decoration: _inputDecoration(
                            hint: _resolveCampus().isEmpty ? 'Enter issuing campus' : 'Campus',
                            icon: Icons.location_city_outlined,
                            suffix: _resolveCampus().isNotEmpty ? const Icon(Icons.check_circle, color: Colors.green, size: 20) : null,
                          ).copyWith(
                            helperText: _resolveCampus().isEmpty
                                ? 'No campus is on record. Enter the correct campus for this loan.'
                                : 'Campus supplied by the staff, book or student record.',
                            helperMaxLines: 2,
                          ),
                        ),

                        const SizedBox(height: 14),

                        TextFormField(
                          controller: _bookIdController,
                          readOnly: true,
                          validator: (value) => value == null || value.trim().isEmpty ? 'Book ID is missing.' : null,
                          decoration: _inputDecoration(hint: 'Book Serial Number / ID', icon: Icons.qr_code_2),
                        ),

                        const SizedBox(height: 22),

                        Row(
                          children: [
                            _dateBox('Borrow Date', _borrowDate, onTap: () => _selectBorrowDate(context)),
                            const SizedBox(width: 14),
                            _dateBox('Expected Due Date', _dueDate),
                          ],
                        ),

                        const SizedBox(height: 14),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Icon(_daysRemaining < 0 ? Icons.warning_amber_rounded : Icons.info_outline, color: _daysRemaining < 0 ? Colors.red : Colors.grey.shade600, size: 16),
                            const SizedBox(width: 6),
                            Text(
                              _daysRemaining < 0 ? 'Overdue by ${_daysRemaining.abs()} days' : '$_daysRemaining days remaining until due date',
                              style: TextStyle(fontWeight: FontWeight.bold, color: _daysRemaining < 0 ? Colors.red : Colors.grey.shade600, fontSize: 13),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // FOOTER
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 20),
                decoration: BoxDecoration(color: Colors.grey.shade50, border: Border(top: BorderSide(color: Colors.grey.shade200))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(false),
                      style: TextButton.styleFrom(foregroundColor: Colors.grey.shade800, padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 17), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero)),
                      child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.bold)),
                    ),

                    const SizedBox(width: 14),

                    ElevatedButton(
                      onPressed: (_isSubmitting || _isLoadingStudents || _verifiedStudent == null) ? null : _submitAssignment,
                      style: ElevatedButton.styleFrom(backgroundColor: _standardGold, foregroundColor: Colors.white, elevation: 0, padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 17), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), disabledBackgroundColor: Colors.grey.shade300),
                      child: _isSubmitting
                          ? const SizedBox(width: 19, height: 19, child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation<Color>(Colors.white)))
                          : const Text('CONFIRM ISSUANCE', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 0.5)),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}