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

import 'package:flutter/material.dart';
import '../../../../core/networks/library_api_service.dart';
import '../../../../core/services/database_service.dart'; 

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);

class BorrowEntryDialog extends StatefulWidget {
  final Map<String, dynamic>? book;

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

  @override
  State<BorrowEntryDialog> createState() => _BorrowEntryDialogState();
}

class _BorrowEntryDialogState extends State<BorrowEntryDialog> {
  final _formKey = GlobalKey<FormState>();
  
  final TextEditingController _studentIdController = TextEditingController();
  final TextEditingController _bookIdController = TextEditingController();
  final TextEditingController _campusController = TextEditingController();
  String _resolvedCampus = '';
  bool _isLoadingCampus = true;

  final TextEditingController _remarksController = TextEditingController();
  
  final DateTime _borrowDate = DateTime.now();
  late DateTime _dueDate;
  
  bool _isLoading = false;
  
  // Real-time validation state for the Student ID field
  bool? _isStudentIdValid; 

  @override
  void initState() {
    super.initState();
    _dueDate = _borrowDate.add(const Duration(days: 14));
    // Auto-fill the Book ID if a book was passed from the directory panel
    if (widget.book != null) {
      _bookIdController.text = _readText(widget.book, ['id', 'book_id', 'accession_no', 'accession_number']);
    }

    // Listen to changes in the Student ID text field for real-time validation
    _studentIdController.addListener(_validateStudentId);
    _loadCampus();
  }

  @override
  void dispose() {
    _studentIdController.removeListener(_validateStudentId);
    _studentIdController.dispose();
    _bookIdController.dispose();
    _remarksController.dispose();
    _campusController.dispose();
    super.dispose();
  }

  String _readText(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) continue;
      final text = value.toString().trim();
      if (text.isNotEmpty && text.toLowerCase() != 'null') return text;
    }
    return '';
  }

  Future<void> _loadCampus() async {
    final bookCampus = _readText(widget.book, [
      'campus', 'campus_name', 'campusName', 'branch', 'branch_name',
    ]);
    var staffCampus = '';
    try {
      final user = await DatabaseService.getLocalUser();
      staffCampus = _readText({'campus': user?.campus}, ['campus']);
    } catch (_) {
      // The book campus or manual entry remains available.
    }
    if (!mounted) return;
    setState(() {
      _resolvedCampus = staffCampus.isNotEmpty ? staffCampus : bookCampus;
      _campusController.text = _resolvedCampus;
      _isLoadingCampus = false;
    });
  }

  // Evaluates the Student ID input as the user types
  void _validateStudentId() {
    final text = _studentIdController.text.trim();
    if (text.isEmpty) {
      if (_isStudentIdValid != null) {
        setState(() => _isStudentIdValid = null); // Reset to default when empty
      }
    } else {
      // 🚀 STRICT RULE: Student ID must strictly contain only numbers and be 8 to 14 digits long
      final isValid = RegExp(r'^\d{8,14}$').hasMatch(text); 
      if (_isStudentIdValid != isValid) {
        setState(() => _isStudentIdValid = isValid);
      }
    }
  }

  Future<void> _selectDueDate(BuildContext context) async {
    if (_isLoading || _isLoadingCampus) return;

    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _dueDate,
      firstDate: DateUtils.dateOnly(_borrowDate),
      lastDate: DateUtils.dateOnly(_borrowDate).add(const Duration(days: 365)),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: const ColorScheme.light(
              primary: _darkGreen, 
              onPrimary: Colors.white,
              onSurface: Colors.black87,
            ),
            dialogTheme: const DialogThemeData(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          ),
          child: child!,
        );
      },
    );
    if (!mounted) return;
    if (picked != null) {
      setState(() {
        // A selected calendar date represents the end of that day.
        // This permits a same-day return without a due time before borrowing.
        _dueDate = DateTime(picked.year, picked.month, picked.day, 23, 59, 59);
      });
    }
  }

  Future<void> _submitForm() async {
    if (_isLoading || _isLoadingCampus) return;
    if (_formKey.currentState?.validate() ?? false) {
      if (!_dueDate.isAfter(_borrowDate)) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Due date must be after borrow date.')),
        );
        return;
      }
      setState(() {
        _isLoading = true;
      });

      try {
        // Payload matches the PHP issuance endpoint and API service.
        final payload = {
          'student_id': _studentIdController.text.trim(),
          'book_id': _bookIdController.text.trim(),
          'borrow_date': _borrowDate.toIso8601String(),
          'campus': _campusController.text.trim(),
          'status': 'Borrowed',
          'due_date': _dueDate.toIso8601String(),
          'remarks': _remarksController.text.trim(),
        };

        // Submit through the existing library API service.
        await LibraryApiService.issueBook(payload);

        if (mounted) {
          final messenger = ScaffoldMessenger.of(context);
          final navigator = Navigator.of(context);
          messenger.showSnackBar(
            const SnackBar(
              content: Text('Book issued successfully. Inventory updated.'),
              backgroundColor: _darkGreen,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          );
          navigator.pop(true);
        }
      } catch (e) {
        if (mounted) {
          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(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  // Helper method to format date as YYYY-MM-DD
  String _formatDate(DateTime date) {
    return "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.zero,
      ),
      backgroundColor: Colors.white,
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: 500,
          maxHeight: MediaQuery.of(context).size.height * 0.92,
        ),
        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: 3)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Expanded(child: Text(
                    'ISSUE NEW BOOK',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.w900,
                      letterSpacing: 1.5,
                    ),
                  )),
                  IconButton(
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),

            // --- FORM BODY ---
            Flexible(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Form Instructions
                      Text(
                        'Enter the student and book details below to initiate a new borrowing transaction.',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
                      ),
                      const SizedBox(height: 24),

                      // Student ID Field
                      _buildLabel('STUDENT ID'),
                      TextFormField(
                        controller: _studentIdController,
                        enabled: !_isLoading,
                        keyboardType: TextInputType.number, // 🚀 Prompts number keyboard on mobile
                        decoration: _buildInputDecoration(
                          'e.g., 2029114996', 
                          Icons.person_search_rounded, 
                          !_isLoading,
                          // Render the dynamic check or "x" icon here
                          suffixIcon: _isStudentIdValid == null
                              ? null
                              : Icon(
                                  _isStudentIdValid! ? Icons.check_circle_rounded : Icons.cancel_rounded,
                                  color: _isStudentIdValid! ? Colors.green : Colors.redAccent,
                                ),
                        ),
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return 'Student ID is required';
                          }
                          if (!RegExp(r'^\d{8,14}$').hasMatch(value.trim())) {
                            return 'Student ID must contain 8 to 14 digits';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 20),

                      // Book ID Field
                      _buildLabel('BOOK ID'),
                      TextFormField(
                        controller: _bookIdController,
                        enabled: !_isLoading,
                        readOnly: widget.book != null, 
                        decoration: _buildInputDecoration('e.g., B-1005', Icons.menu_book_rounded, !_isLoading && widget.book == null),
                        validator: (value) {
                          if (_readText({'id': value}, ['id']).isEmpty) {
                            return 'Book ID is required';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 20),

                      // Campus field
                      _buildLabel('ISSUING CAMPUS'),
                      TextFormField(
                        controller: _campusController,
                        enabled: !_isLoading && !_isLoadingCampus,
                        readOnly: _resolvedCampus.isNotEmpty,
                        validator: (value) => _readText({'campus': value}, ['campus']).isEmpty
                            ? 'Enter the correct issuing campus' : null,
                        decoration: _buildInputDecoration(
                          _isLoadingCampus ? 'Loading campus...' : 'Enter issuing campus',
                          Icons.location_city_outlined,
                          !_isLoading && !_isLoadingCampus && _resolvedCampus.isEmpty,
                        ).copyWith(
                          helperText: _isLoadingCampus
                              ? 'Checking staff and book records.'
                              : _resolvedCampus.isEmpty
                                  ? 'No campus is on record. Enter the correct campus for this loan.'
                                  : 'Campus supplied by the staff or book record.',
                          helperMaxLines: 3,
                        ),
                      ),
                      const SizedBox(height: 20),

                      // Dates Row
                      Row(
                        children: [
                          // Borrow Date (Read-Only)
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabel('BORROW DATE'),
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade100,
                                    border: Border.all(color: Colors.grey.shade300),
                                  ),
                                  child: Row(
                                    children: [
                                      const Icon(Icons.calendar_today_rounded, color: Colors.grey, size: 20),
                                      const SizedBox(width: 12),
                                      Flexible(child: Text(
                                        _formatDate(_borrowDate),
                                        style: TextStyle(color: Colors.grey.shade800, fontWeight: FontWeight.w600),
                                      )),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(width: 16),
                          
                          // Due Date (Clickable)
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabel('DUE DATE'),
                                InkWell(
                                  onTap: _isLoading ? null : () => _selectDueDate(context),
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                                    decoration: BoxDecoration(
                                      color: _isLoading ? Colors.grey.shade100 : Colors.white,
                                      border: Border.all(color: Colors.grey.shade300),
                                    ),
                                    child: Row(
                                      children: [
                                        Icon(Icons.event_rounded, color: _isLoading ? Colors.grey : _darkGreen, size: 20),
                                        const SizedBox(width: 12),
                                        Flexible(child: Text(
                                          _formatDate(_dueDate),
                                          style: TextStyle(
                                            color: _isLoading ? Colors.grey : Colors.black87, 
                                            fontWeight: FontWeight.w600
                                          ),
                                        )),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 20),

                      // Remarks (Optional)
                      _buildLabel('REMARKS (OPTIONAL)'),
                      TextFormField(
                        controller: _remarksController,
                        enabled: !_isLoading,
                        maxLines: 2,
                        decoration: _buildInputDecoration('Add any condition notes or remarks...', Icons.notes_rounded, !_isLoading),
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // --- FOOTER ACTIONS ---
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                border: Border(top: BorderSide(color: Colors.grey.shade200)),
              ),
              child: Wrap(
                alignment: WrapAlignment.end,
                spacing: 12,
                runSpacing: 8,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.grey.shade700,
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                    ),
                    child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                  ),
                  ElevatedButton.icon(
                    onPressed: (_isLoading || _isLoadingCampus) ? null : _submitForm,
                    icon: _isLoading 
                        ? const SizedBox(
                            width: 20, 
                            height: 20, 
                            child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)
                          )
                        : const Icon(Icons.check_circle_outline_rounded, color: Colors.white),
                    label: Text(
                      _isLoading ? 'PROCESSING...' : 'AUTHORIZE ISSUE',
                      style: const 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: 20),
                      disabledBackgroundColor: _standardGold.withOpacity(0.5),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // --- REUSABLE UI HELPERS ---

  Widget _buildLabel(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Text(
        text,
        style: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: _darkGreen,
          letterSpacing: 1.0,
        ),
      ),
    );
  }

  // Updated to accept an optional suffixIcon widget
  InputDecoration _buildInputDecoration(String hint, IconData icon, bool enabled, {Widget? suffixIcon}) {
    return InputDecoration(
      hintText: hint,
      prefixIcon: Icon(icon, color: Colors.grey),
      suffixIcon: suffixIcon, // Applies the dynamic icon
      filled: true,
      fillColor: enabled ? Colors.white : Colors.grey.shade100,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      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),
      ),
      errorBorder: const OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.red, width: 1),
      ),
      focusedErrorBorder: const OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.red, width: 2),
      ),
      disabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
    );
  }
}