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

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../../core/networks/library_api_service.dart'; // Ensure this points to your API service

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

class BorrowingEntryDialog extends StatefulWidget {
  const BorrowingEntryDialog({super.key});

  @override
  State<BorrowingEntryDialog> createState() => _BorrowingEntryDialogState();
}

class _BorrowingEntryDialogState extends State<BorrowingEntryDialog> {
  final _formKey = GlobalKey<FormState>();
  
  final TextEditingController _studentNumberController = TextEditingController();
  final TextEditingController _bookSerialController = TextEditingController();
  
  String? _selectedDepartment;
  bool _isLoading = false;

  final List<String> _departments = [
    'Computer Science',
    'Business Administration',
    'Nursing',
    'Education',
  ];

  DateTime? _borrowDate = DateTime.now();
  DateTime? _dueDate = DateTime.now().add(const Duration(days: 14)); // Default 2 weeks

  @override
  void dispose() {
    _studentNumberController.dispose();
    _bookSerialController.dispose();
    super.dispose();
  }

  Future<void> _selectDate(BuildContext context, bool isBorrowDate) async {
    if (_isLoading) return; // Prevent interaction while loading

    final DateTime initialDate = isBorrowDate 
        ? (_borrowDate ?? DateTime.now()) 
        : (_dueDate ?? DateTime.now().add(const Duration(days: 14)));
        
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2101),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: const ColorScheme.light(
              primary: _darkGreen,
              onPrimary: Colors.white,
              onSurface: Colors.black,
            ),
            dialogTheme: const DialogThemeData(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          ),
          child: child!,
        );
      },
    );

    if (picked != null) {
      setState(() {
        if (isBorrowDate) {
          _borrowDate = picked;
          // Auto-update due date to ensure it is not before borrow date
          if (_dueDate != null && _dueDate!.isBefore(_borrowDate!)) {
            _dueDate = _borrowDate!.add(const Duration(days: 14));
          }
        } else {
          _dueDate = picked;
        }
      });
    }
  }

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      if (_borrowDate == null || _dueDate == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please select valid dates.'), 
            backgroundColor: Colors.redAccent,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
          ),
        );
        return;
      }
      
      setState(() {
        _isLoading = true;
      });

      try {
        final borrowingData = {
          'student_id': _studentNumberController.text.trim(),
          'book_id': _bookSerialController.text.trim(),
          'department': _selectedDepartment,
          'issue_date': _borrowDate!.toIso8601String(),
          'due_date': _dueDate!.toIso8601String(),
          'status': 'ISSUED',
        };

        // Call the Python FastAPI backend via the service
        await LibraryApiService.issueBook(borrowingData);

        if (mounted) {
          // Pop with 'true' to trigger the refresh cascade in the dashboard
          Navigator.of(context).pop(true);
          
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Book issued successfully.'),
              backgroundColor: _darkGreen,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          );
        }
      } catch (error) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Issuance Failed: $error'),
              backgroundColor: Colors.redAccent,
              behavior: SnackBarBehavior.floating,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          );
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      backgroundColor: Colors.white,
      child: Container(
        width: 500,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        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: 16,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 1.2,
                    ),
                  ),
                  IconButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                    splashRadius: 20,
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),
            
            // --- FORM BODY ---
            Flexible(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(32.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildTextField(
                        controller: _studentNumberController,
                        label: 'Student Number',
                        icon: Icons.badge_rounded,
                        enabled: !_isLoading,
                        validator: (value) => value == null || value.trim().isEmpty ? 'Required field' : null,
                      ),
                      const SizedBox(height: 24),
                      
                      _buildTextField(
                        controller: _bookSerialController,
                        label: 'Book Serial Number / ID',
                        icon: Icons.qr_code_rounded,
                        enabled: !_isLoading,
                        validator: (value) => value == null || value.trim().isEmpty ? 'Required field' : null,
                      ),
                      const SizedBox(height: 24),
                      
                      DropdownButtonFormField<String>(
                        initialValue: _selectedDepartment,
                        decoration: _inputDecoration('Student Department', Icons.account_tree_rounded),
                        items: _departments.map((dept) {
                          return DropdownMenuItem(value: dept, child: Text(dept));
                        }).toList(),
                        onChanged: _isLoading ? null : (value) => setState(() => _selectedDepartment = value),
                        validator: (value) => value == null ? 'Please select a department' : null,
                        icon: const Icon(Icons.keyboard_arrow_down_rounded, color: _darkGreen),
                      ),
                      const SizedBox(height: 24),

                      // --- DATES SECTION ---
                      Row(
                        children: [
                          Expanded(
                            child: _buildDatePickerField(
                              label: 'Borrow Date',
                              date: _borrowDate,
                              onTap: () => _selectDate(context, true),
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: _buildDatePickerField(
                              label: 'Expected Due Date',
                              date: _dueDate,
                              onTap: () => _selectDate(context, false),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // --- FOOTER ACTIONS ---
            Container(
              padding: const EdgeInsets.all(24.0),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                border: Border(top: BorderSide(color: Colors.grey.shade200, width: 1)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.grey.shade700,
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                    ),
                    child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.bold)),
                  ),
                  const SizedBox(width: 16),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _submitForm,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _standardGold,
                      foregroundColor: Colors.white,
                      elevation: 0,
                      padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 18),
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                      disabledBackgroundColor: _standardGold.withOpacity(0.5),
                    ),
                    child: _isLoading
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : const Text('CONFIRM ISSUANCE', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    required String? Function(String?) validator,
    bool enabled = true,
  }) {
    return TextFormField(
      controller: controller,
      enabled: enabled,
      decoration: _inputDecoration(label, icon),
      validator: validator,
      cursorColor: _darkGreen,
    );
  }

  Widget _buildDatePickerField({
    required String label,
    required DateTime? date,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      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, width: 1),
          borderRadius: BorderRadius.zero,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                ),
                const SizedBox(height: 4),
                Text(
                  date != null ? DateFormat('MMM dd, yyyy').format(date) : 'Select Date',
                  style: TextStyle(
                    color: _isLoading ? Colors.grey : (date != null ? Colors.black87 : Colors.grey),
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            Icon(Icons.calendar_month_rounded, color: Colors.grey.shade500, size: 20),
          ],
        ),
      ),
    );
  }

  InputDecoration _inputDecoration(String label, IconData icon) {
    return InputDecoration(
      labelText: label,
      labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14),
      prefixIcon: Icon(icon, color: Colors.grey.shade500, size: 20),
      filled: true,
      fillColor: _isLoading ? Colors.grey.shade100 : Colors.white,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      border: const OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.grey),
      ),
      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.redAccent, width: 1),
      ),
      disabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.zero,
        borderSide: BorderSide(color: Colors.grey.shade200),
      ),
    );
  }
}