// lib/features/admin/tabs/positions/staff/staff_directory_sub_tab.dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../../../core/networks/api_client.dart';

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

Widget _responsiveStaffFormFields(BuildContext context, List<Widget> fields) {
  return LayoutBuilder(builder: (context, bounds) {
    const gap = 16.0;
    final fieldWidth = bounds.maxWidth < 560
        ? bounds.maxWidth
        : (bounds.maxWidth - gap * (fields.length - 1)) / fields.length;
    return Wrap(
      spacing: gap,
      runSpacing: gap,
      children: [for (final field in fields) SizedBox(width: fieldWidth, child: field)],
    );
  });
}



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

  @override
  State<StaffDirectorySubTab> createState() => _StaffDirectorySubTabState();
}

class _StaffDirectorySubTabState extends State<StaffDirectorySubTab> {
  final ScrollController _horizontalScrollController = ScrollController();
  List<Map<String, dynamic>> _existingStaff = [];
  
  bool _isFetchingStaff = true;
  bool _isOpeningDialog = false; 

  @override
  void initState() {
    super.initState();
    ApiClient.dataChanges.addListener(_onStaffDataChange);
    _loadStaff();
  }

  void _onStaffDataChange() {
    final change = ApiClient.dataChanges.value;
    final endpoint = Uri.parse('${ApiClient.baseUrl}/api/users.php?role=staff');
    if (change == null || change.isMutation ||
        !ApiClient.sameApiFamily(change.url, endpoint)) return;
    Future<void>.delayed(const Duration(milliseconds: 100), () {
      if (mounted) _loadStaff(refresh: false, showLoading: false);
    });
  }

  Future<void> _loadStaff({bool refresh = false, bool showLoading = true}) async {
    if (showLoading && _existingStaff.isEmpty) setState(() => _isFetchingStaff = true);
    try {
      final staff = await ApiClient.getStaff(refresh: refresh); 
      if (mounted) {
        setState(() {
         _existingStaff = List<Map<String, dynamic>>.from(staff);
         _isFetchingStaff = false;
       });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isFetchingStaff = false);
        if (showLoading) _showSnackBar('Failed to load staff records.', Colors.redAccent);
      }
    }
  }

  @override
  void dispose() {
    ApiClient.dataChanges.removeListener(_onStaffDataChange);
    _horizontalScrollController.dispose(); 
    super.dispose();
  }

  void _showSnackBar(String message, Color color) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
        backgroundColor: color,
        behavior: SnackBarBehavior.floating,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      ),
    );
  }

  Widget _buildAvatarImage(String? imageStr, {double radius = 18}) {
    if (imageStr == null || imageStr.isEmpty) return Icon(Icons.person, color: Colors.grey.shade500, size: radius);
    if (imageStr.startsWith('http')) return Image.network(imageStr, fit: BoxFit.cover, errorBuilder: (_,_,_) => Icon(Icons.person, color: Colors.grey.shade500));
    try {
      return Image.memory(base64Decode(imageStr), fit: BoxFit.cover, errorBuilder: (_,_,_) => Icon(Icons.person, color: Colors.grey.shade500));
    } catch (e) {
      return Icon(Icons.person, color: Colors.grey.shade500, size: radius);
    }
  }

  void _confirmDelete(Map<String, dynamic> staffData) {
    bool isDeleting = false;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            backgroundColor: Colors.white,
            title: Row(
              children: [
                const Icon(Icons.warning_amber_rounded, color: Colors.redAccent),
                const SizedBox(width: 8),
                const Text('Remove Staff', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
              ],
            ),
            content: Text('Are you sure you want to remove ${staffData['full_name']}? This action cannot be undone.'),
            actions: [
              TextButton(
                onPressed: isDeleting ? null : () => Navigator.pop(ctx),
                child: Text('CANCEL', style: TextStyle(color: Colors.grey.shade600, fontWeight: FontWeight.bold)),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.redAccent, foregroundColor: Colors.white, elevation: 0,
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                ),
                onPressed: isDeleting ? null : () async {
                  setDialogState(() => isDeleting = true);
                  final success = await ApiClient.deleteStaff(staffData['id']);
                  if (success && mounted) {
                    Navigator.pop(ctx);
                    _showSnackBar('${staffData['full_name']} has been removed.', Colors.black87);
                    _loadStaff(); 
                  } else {
                    setDialogState(() => isDeleting = false);
                    _showSnackBar('Failed to delete staff.', Colors.redAccent);
                  }
                },
                child: isDeleting ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) : const Text('DELETE'),
              ),
            ],
          );
        }
      ),
    );
  }

  void _openAddStaffDialog() async {
    setState(() => _isOpeningDialog = true);
    
    await Future.delayed(const Duration(milliseconds: 400));
    
    if (mounted) setState(() => _isOpeningDialog = false);

    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => const AddStaffDialog(),
    );
    if (result == true) {
      _loadStaff(); 
    }
  }

  void _openEditStaffDialog(Map<String, dynamic> staffData) async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => AddStaffDialog(staffToEdit: staffData),
    );
    if (result == true) {
      _loadStaff(); 
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(MediaQuery.sizeOf(context).width < 600 ? 12.0 : 32.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Wrap(
            alignment: WrapAlignment.spaceBetween,
            spacing: 12,
            runSpacing: 12,
            crossAxisAlignment: WrapCrossAlignment.center,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('STAFF DIRECTORY', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: Colors.grey.shade800, letterSpacing: 1.5)),
                  const SizedBox(width: 16),
                  if (_isFetchingStaff) const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)),
                ],
              ),
              Tooltip(
                message: 'Refresh staff',
                child: IconButton(
                  onPressed: _isFetchingStaff ? null : () => _loadStaff(refresh: true),
                  icon: _isFetchingStaff
                      ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen))
                      : const Icon(Icons.refresh_rounded, color: _darkGreen),
                  style: IconButton.styleFrom(
                    backgroundColor: _darkGreen.withOpacity(.08),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                  ),
                ),
              ),
              ElevatedButton.icon(
                onPressed: _isOpeningDialog ? null : _openAddStaffDialog,
                icon: _isOpeningDialog 
                    ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                    : const Icon(Icons.add_box_rounded, color: Colors.white),
                label: Text(
                  _isOpeningDialog ? 'LOADING...' : 'ADD STAFF', 
                  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: 22),
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),
          
          Expanded(
            child: Container(
              decoration: BoxDecoration(color: Colors.white, border: Border.all(color: Colors.grey.shade300, width: 1)),
              child: _existingStaff.isEmpty && !_isFetchingStaff
                ? const Center(child: Text("No staff data available.", style: TextStyle(color: Colors.grey)))
                : LayoutBuilder(
                    builder: (context, constraints) {
                      return SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: SingleChildScrollView(
                          controller: _horizontalScrollController, 
                          scrollDirection: Axis.horizontal,
                          child: ConstrainedBox(
                            constraints: BoxConstraints(minWidth: constraints.maxWidth),
                            child: DataTable(
                              headingRowColor: WidgetStateProperty.resolveWith((states) => _darkGreen),
                              headingTextStyle: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 0.5),
                              dataRowMinHeight: 65, dataRowMaxHeight: 65, dividerThickness: 1,
                              columns: const [
                                DataColumn(label: Text('PROFILE')),
                                DataColumn(label: Text('FULL NAME')),
                                DataColumn(label: Text('EMAIL')),
                                DataColumn(label: Text('PHONE')),
                                DataColumn(label: Text('CAMPUS')),
                                DataColumn(label: Text('ACTIONS')),
                              ],
                              rows: _existingStaff.map((staff) {
                                return DataRow(
                                  cells: [
                                    DataCell(
                                      Container(
                                        width: 40, height: 40,
                                        decoration: BoxDecoration(color: Colors.grey.shade200, shape: BoxShape.rectangle, border: Border.all(color: Colors.grey.shade300)),
                                        clipBehavior: Clip.hardEdge,
                                        child: _buildAvatarImage(staff['profile_picture']),
                                      ),
                                    ),
                                    DataCell(Text(staff['full_name'] ?? '', style: const TextStyle(fontWeight: FontWeight.w600))),
                                    DataCell(Text(staff['email'] ?? '', style: TextStyle(color: Colors.grey.shade700))),
                                    DataCell(Text(staff['phone'] ?? '-', style: TextStyle(color: Colors.grey.shade700))),
                                    DataCell(Text(staff['campus'] ?? '-', style: TextStyle(color: Colors.grey.shade700))),
                                    DataCell(
                                      Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: const Icon(Icons.edit_outlined, size: 18, color: Colors.blueAccent), 
                                            onPressed: () => _openEditStaffDialog(staff), 
                                            splashRadius: 20
                                          ),
                                          IconButton(
                                            icon: const Icon(Icons.delete_outline, size: 18, color: Colors.redAccent), 
                                            onPressed: () => _confirmDelete(staff), 
                                            splashRadius: 20
                                          ),
                                        ],
                                      )
                                    ),
                                  ],
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      );
                    }
                  ),
            ),
          ),
        ],
      ),
    );
  }
}

// =====================================================================
// ADD & EDIT STAFF DIALOG
// =====================================================================
class AddStaffDialog extends StatefulWidget {
  final Map<String, dynamic>? staffToEdit; 

  const AddStaffDialog({super.key, this.staffToEdit});

  @override
  State<AddStaffDialog> createState() => _AddStaffDialogState();
}

class _AddStaffDialogState extends State<AddStaffDialog> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  
  late TextEditingController _fullNameController;
  late TextEditingController _emailController;
  late TextEditingController _nrcController;
  late TextEditingController _phoneController;
  late TextEditingController _passwordController;
  
  Uint8List? _profileImageBytes;
  String? _existingProfileImageStr;
  
  String _selectedGender = 'Male';
  bool _isObscured = true;
  bool _isLoading = false;

  final List<String> _genderOptions = ['Male', 'Female', 'Other'];
  String _selectedCountryCode = '+260';
  String _selectedCountry = 'Zambia';
  
  final List<Map<String, String>> _countries = [
    {'name': 'Zambia', 'code': '+260', 'flag': '🇿🇲'},
    {'name': 'Zimbabwe', 'code': '+263', 'flag': '🇿🇼'},
    {'name': 'South Africa', 'code': '+27', 'flag': '🇿🇦'},
    {'name': 'Botswana', 'code': '+267', 'flag': '🇧🇼'},
    {'name': 'Namibia', 'code': '+264', 'flag': '🇳🇦'},
    {'name': 'Malawi', 'code': '+265', 'flag': '🇲🇼'},
  ];

  // --- DYNAMIC DATABASE DROPDOWN VARIABLES ---
  bool _isFetchingDropdowns = true;
  List<String> _dbCampuses = [];
  List<String> _dbSchools = [];
  List<String> _dbDepartments = [];
  
  String? _selectedCampus;
  String? _selectedSchool;
  String? _selectedDepartment;

  @override
  void initState() {
    super.initState();
    
    // Initialize Controllers
    _fullNameController = TextEditingController(text: widget.staffToEdit?['full_name'] ?? '');
    _emailController = TextEditingController(text: widget.staffToEdit?['email'] ?? '');
    _nrcController = TextEditingController(text: widget.staffToEdit?['nrc'] ?? '');
    _passwordController = TextEditingController(); 
    
    _existingProfileImageStr = widget.staffToEdit?['profile_picture'];
    
    String rawPhone = widget.staffToEdit?['phone'] ?? '';
    if (rawPhone.contains(' ')) {
      final parts = rawPhone.split(' ');
      String potentialCode = parts[0];
      
      if (_countries.any((c) => c['code'] == potentialCode)) {
        _selectedCountryCode = potentialCode;
        _selectedCountry = _countries.firstWhere((c) => c['code'] == potentialCode)['name']!;
      } else {
        _selectedCountryCode = '+260';
        _selectedCountry = 'Zambia';
      }
      
      _phoneController = TextEditingController(text: parts.sublist(1).join(' '));
    } else {
      _phoneController = TextEditingController(text: rawPhone);
    }

    if (widget.staffToEdit != null) {
      if (_genderOptions.contains(widget.staffToEdit!['gender'])) {
        _selectedGender = widget.staffToEdit!['gender'];
      }
    }

    _fetchDatabaseDropdowns();
  }

  @override
  void dispose() {
    _fullNameController.dispose();
    _emailController.dispose();
    _nrcController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  List<String> _directoryNames(List<dynamic> rows) {
    return rows
        .whereType<Map>()
        .map((row) => (row['name'] ?? '').toString().trim())
        .where((name) => name.isNotEmpty && name.toLowerCase() != 'null')
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
  }

  String _normalizeDepartmentName(String value) {
    var text = value.toLowerCase().trim();
    text = text.replaceAll(RegExp(r'[^a-z0-9]+'), ' ');
    final ignored = <String>{'department', 'dept', 'of', 'the'};
    final words = text
        .split(RegExp(r'\s+'))
        .where((word) => word.isNotEmpty && !ignored.contains(word))
        .toList();
    return words.join(' ');
  }

  String? _matchDepartmentFromDirectory(dynamic rawValue) {
    final raw = (rawValue ?? '').toString().trim();
    if (raw.isEmpty || raw.toLowerCase() == 'null') return null;

    for (final name in _dbDepartments) {
      if (name.toLowerCase() == raw.toLowerCase()) return name;
    }

    final normalized = _normalizeDepartmentName(raw);
    if (normalized.isEmpty) return null;

    final normalizedMatches = _dbDepartments
        .where((name) => _normalizeDepartmentName(name) == normalized)
        .toList();
    if (normalizedMatches.length == 1) return normalizedMatches.first;

    final containsMatches = _dbDepartments.where((name) {
      final candidate = _normalizeDepartmentName(name);
      return candidate.isNotEmpty &&
          (candidate.contains(normalized) || normalized.contains(candidate));
    }).toList();
    return containsMatches.length == 1 ? containsMatches.first : null;
  }

  Future<void> _fetchDatabaseDropdowns() async {
    if (!mounted) return;
    setState(() => _isFetchingDropdowns = true);

    try {
      final results = await Future.wait<List<dynamic>>([
        ApiClient.getCampuses(),
        ApiClient.getSchools(),
        ApiClient.getDepartments(),
      ]);

      final campuses = _directoryNames(results[0]);
      final schools = _directoryNames(results[1]);
      final departments = _directoryNames(results[2]);

      if (departments.isEmpty) {
        throw StateError('The Departments directory is empty. Add departments before assigning staff.');
      }

      if (!mounted) return;
      setState(() {
        _dbCampuses = campuses;
        _dbSchools = schools;
        _dbDepartments = departments;
        _applySafeDropdownDefaults();
        _isFetchingDropdowns = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _dbCampuses = [];
        _dbSchools = [];
        _dbDepartments = [];
        _selectedCampus = null;
        _selectedSchool = null;
        _selectedDepartment = null;
        _isFetchingDropdowns = false;
      });
      _showSnackBar(
        'Unable to load Campus, School or Department directories. No placeholder departments will be used. ${e.toString()}',
        Colors.redAccent,
      );
    }
  }

  void _applySafeDropdownDefaults() {
    if (widget.staffToEdit == null) return;

    final existingCampus = (widget.staffToEdit!['campus'] ?? '').toString().trim();
    final existingSchool = (widget.staffToEdit!['school'] ?? '').toString().trim();
    final existingDept = widget.staffToEdit!['department_name'] ??
        widget.staffToEdit!['program'];

    if (existingCampus.isNotEmpty && _dbCampuses.contains(existingCampus)) {
      _selectedCampus = existingCampus;
    }

    if (existingSchool.isNotEmpty && _dbSchools.contains(existingSchool)) {
      _selectedSchool = existingSchool;
    }

    // Resolve legacy values such as "Computer Science" against canonical
    // names such as "Department of Computer Science" without inventing
    // values that do not exist in the departments table.
    _selectedDepartment = _matchDepartmentFromDirectory(existingDept);
  }

  Future<void> _pickImage() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 50);
      if (pickedFile != null) {
        final bytes = await pickedFile.readAsBytes();
        setState(() => _profileImageBytes = bytes);
      }
    } catch (e) {
      if (mounted) _showSnackBar('Failed to pick image.', Colors.redAccent);
    }
  }

  Widget _buildAvatarPreview() {
    if (_profileImageBytes != null) {
      return Image.memory(_profileImageBytes!, fit: BoxFit.cover, width: 140, height: 140);
    } else if (_existingProfileImageStr != null && _existingProfileImageStr!.isNotEmpty) {
      try {
        if (_existingProfileImageStr!.startsWith('http')) {
          return Image.network(_existingProfileImageStr!, fit: BoxFit.cover, width: 140, height: 140);
        } else {
          return Image.memory(base64Decode(_existingProfileImageStr!), fit: BoxFit.cover, width: 140, height: 140);
        }
      } catch (e) {
        return Icon(Icons.person, size: 55, color: Colors.grey.shade400);
      }
    }
    return Icon(Icons.person, size: 55, color: Colors.grey.shade400);
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      if (_selectedCampus == null || _selectedSchool == null || _selectedDepartment == null) {
        _showSnackBar('Please select Campus, School, and Department.', Colors.redAccent);
        return;
      }

      setState(() => _isLoading = true);

      try {
        String base64Image = _existingProfileImageStr ?? '';
        if (_profileImageBytes != null) {
          base64Image = base64Encode(_profileImageBytes!);
        }

        final staffData = {
          'full_name': _fullNameController.text.trim(),
          'email': _emailController.text.trim(),
          'nrc': _nrcController.text.trim(),
          'phone': "$_selectedCountryCode ${_phoneController.text.trim()}",
          'gender': _selectedGender,
          'country': _selectedCountry,
          'campus': _selectedCampus,
          'school': _selectedSchool,
          'program': _selectedDepartment, 
          'role': 'staff', 
          'profile_picture': base64Image, 
        };

        if (_passwordController.text.isNotEmpty) {
          staffData['password'] = _passwordController.text;
        }

        bool success = false;
        if (widget.staffToEdit == null) {
           if (_passwordController.text.isEmpty) {
             _showSnackBar('Initial password is required for new staff.', Colors.redAccent);
             setState(() => _isLoading = false);
             return;
           }
           staffData['password'] = _passwordController.text;
           success = await ApiClient.addStaff(staffData);
        } else {
           success = await ApiClient.updateStaff(widget.staffToEdit!['id'], staffData);
        }

        if (success && mounted) {
          _showSnackBar(widget.staffToEdit == null ? 'New staff member provisioned successfully.' : 'Staff updated successfully.', _darkGreen);
          Navigator.pop(context, true); 
        } else {
          throw Exception("Server returned false");
        }
      } catch (e) {
        if (mounted) _showSnackBar(widget.staffToEdit == null ? 'Failed to add staff member.' : 'Failed to update staff member.', Colors.redAccent);
      } finally {
        if (mounted) setState(() => _isLoading = false);
      }
    }
  }

  void _showSnackBar(String message, Color color) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
        backgroundColor: color,
        behavior: SnackBarBehavior.floating,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Row(
      children: [
        Container(width: 4, height: 18, color: _standardGold),
        const SizedBox(width: 8),
        Text(title, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.grey.shade800, letterSpacing: 0.5)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.staffToEdit != null;
    final screenWidth = MediaQuery.sizeOf(context).width;
    final compact = screenWidth < 600;

    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 12 : 40, vertical: 16),
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      backgroundColor: Colors.white,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: compact ? screenWidth - 24 : 800, maxHeight: MediaQuery.sizeOf(context).height * 0.9),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 14 : 24, vertical: 20),
              decoration: const BoxDecoration(
                color: _darkGreen,
                border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(isEditing ? 'EDIT STAFF RECORD' : 'PROVISION NEW STAFF', style: TextStyle(color: Colors.white, fontSize: compact ? 14 : 18, fontWeight: FontWeight.w900, letterSpacing: compact ? .6 : 1.5)),
                  IconButton(
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),
            
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 16 : 32),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // --- BEAUTIFUL CIRCULAR AVATAR PICKER ---
                      Center(
                        child: GestureDetector(
                          onTap: _pickImage,
                          child: Stack(
                            alignment: Alignment.bottomRight,
                            children: [
                              Container(
                                width: 130, 
                                height: 130,
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade50,
                                  shape: BoxShape.circle, // Circular shape!
                                  border: Border.all(color: _standardGold.withOpacity(0.5), width: 3),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.08), 
                                      blurRadius: 15, 
                                      offset: const Offset(0, 5),
                                    )
                                  ]
                                ),
                                child: ClipOval( // Ensures the image inside is also circular
                                  child: _profileImageBytes != null || (_existingProfileImageStr != null && _existingProfileImageStr!.isNotEmpty)
                                      ? _buildAvatarPreview()
                                      : Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Icon(Icons.person_rounded, size: 50, color: Colors.grey.shade400),
                                            const SizedBox(height: 8),
                                            Text('Upload', style: TextStyle(color: Colors.grey.shade500, fontSize: 12, fontWeight: FontWeight.bold)),
                                          ],
                                        ),
                                ),
                              ),
                              // Floating Camera Badge
                              Positioned(
                                bottom: 4, right: 4,
                                child: Container(
                                  padding: const EdgeInsets.all(10),
                                  decoration: BoxDecoration(
                                    color: _darkGreen, 
                                    shape: BoxShape.circle, // Circular camera badge
                                    border: Border.all(color: Colors.white, width: 3),
                                    boxShadow: [
                                      BoxShadow(color: Colors.black.withOpacity(0.15), blurRadius: 8, offset: const Offset(0, 4))
                                    ]
                                  ),
                                  child: const Icon(Icons.camera_alt_rounded, color: Colors.white, size: 18),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 48),

                      _buildFlatTextField(controller: _fullNameController, label: 'Full Name', icon: Icons.person_outline, validator: (v) => v!.isEmpty ? 'Required' : null),
                      const SizedBox(height: 16),
                      
                      _buildFlatTextField(controller: _emailController, label: 'Email Address', icon: Icons.email_outlined, keyboardType: TextInputType.emailAddress, validator: (v) => v!.contains('@') ? null : 'Invalid email'),
                      const SizedBox(height: 16),

                      _responsiveStaffFormFields(context, [
            _buildFlatTextField(controller: _nrcController, label: 'NRC', icon: Icons.badge_outlined),
            _buildFlatDropdown(
                              label: 'Gender', icon: Icons.people_outline, currentValue: _selectedGender, items: _genderOptions,
                              onChanged: (val) { if (val != null) setState(() => _selectedGender = val); }
                            ),
          ]),
                      const SizedBox(height: 16),

                      _buildFlatPhoneInput(
                        controller: _phoneController, currentCode: _selectedCountryCode,
                        onCodeChanged: (val) {
                          if (val != null) setState(() { _selectedCountryCode = val; _selectedCountry = _countries.firstWhere((c) => c['code'] == val)['name']!; });
                        },
                      ),
                      const SizedBox(height: 16),

                      _isFetchingDropdowns
                          ? Container(
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300)),
                              child: const Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)),
                                  SizedBox(width: 16),
                                  Text("Fetching Campuses, Schools & Departments..."),
                                ],
                              ),
                            )
                           : LayoutBuilder(builder: (context, bounds) {
                              final gap = 16.0;
                              final fieldWidth = bounds.maxWidth < 640
                                  ? bounds.maxWidth
                                  : (bounds.maxWidth - gap * 2) / 3;
                              return Wrap(
                                spacing: gap,
                                runSpacing: gap,
                                children: [
                                  for (final field in <Widget>[
                                    _buildFlatDropdown(
                                      label: 'Campus', icon: Icons.domain,
                                      currentValue: _selectedCampus, items: _dbCampuses,
                                      onChanged: (val) => setState(() => _selectedCampus = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                    _buildFlatDropdown(
                                      label: 'School', icon: Icons.account_balance,
                                      currentValue: _selectedSchool, items: _dbSchools,
                                      onChanged: (val) => setState(() => _selectedSchool = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                    _buildFlatDropdown(
                                      label: 'Department', icon: Icons.book_outlined,
                                      currentValue: _selectedDepartment, items: _dbDepartments,
                                      onChanged: (val) => setState(() => _selectedDepartment = val),
                                      validator: (val) => val == null ? 'Required' : null,
                                    ),
                                  ])
                                    SizedBox(width: fieldWidth, child: field),
                                ],
                              );
                            }),
                      const SizedBox(height: 16),
                      
                      _buildFlatTextField(
                        controller: _passwordController, 
                        label: isEditing ? 'Change Password (Leave blank to keep current)' : 'Initial Password', 
                        icon: Icons.lock_outline, 
                        isPassword: true,
                        validator: (v) {
                          if (isEditing && v!.isEmpty) return null; 
                          if (v!.isNotEmpty && v.length < 6) return 'Min 6 chars';
                          return null;
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 12 : 24, vertical: 12),
              decoration: BoxDecoration(color: Colors.grey.shade50, border: Border(top: BorderSide(color: Colors.grey.shade200))),
              child: Wrap(
                alignment: WrapAlignment.end,
                spacing: 8,
                runSpacing: 8,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(false),
                    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)),
                  ),
                  const SizedBox(width: 16),
                  ElevatedButton.icon(
                    onPressed: _isLoading ? null : _submitForm,
                    icon: _isLoading 
                        ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : const Icon(Icons.save_rounded, color: Colors.white),
                    label: Text(
                      _isLoading ? 'SAVING...' : 'SAVE RECORD',
                      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),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFlatTextField({required TextEditingController controller, required String label, required IconData icon, bool isPassword = false, TextInputType keyboardType = TextInputType.text, String? Function(String?)? validator}) {
    return TextFormField(
      controller: controller, obscureText: isPassword ? _isObscured : false, keyboardType: keyboardType, validator: validator, cursorColor: _darkGreen,
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14),
        prefixIcon: Icon(icon, color: Colors.grey.shade500, size: 20),
        suffixIcon: isPassword ? IconButton(icon: Icon(_isObscured ? Icons.visibility_off_outlined : Icons.visibility_outlined, size: 20), color: Colors.grey.shade500, onPressed: () => setState(() => _isObscured = !_isObscured)) : null,
        filled: true, fillColor: Colors.white,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        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)),
      ),
    );
  }

  Widget _buildFlatPhoneInput({required TextEditingController controller, required String currentCode, required ValueChanged<String?> onCodeChanged}) {
    return Container(
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.zero, border: Border.all(color: Colors.grey.shade300)),
      child: Row(
        children: [
          Padding(padding: const EdgeInsets.only(left: 12.0), child: Icon(Icons.phone_outlined, color: Colors.grey.shade500, size: 20)),
          const SizedBox(width: 8),
          Expanded(
            flex: 4,
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                isExpanded: true, value: currentCode, icon: Icon(Icons.arrow_drop_down, color: Colors.grey.shade600),
                style: TextStyle(color: Colors.grey.shade800, fontSize: 14, fontWeight: FontWeight.w500),
                dropdownColor: Colors.white, onChanged: onCodeChanged,
                items: _countries.map((c) => DropdownMenuItem(value: c['code'], child: Text("${c['flag']} ${c['code']}"))).toList(),
              ),
            ),
          ),
          const SizedBox(width: 8),
          Container(height: 24, width: 1, color: Colors.grey.shade300),
          Expanded(
            flex: 6,
            child: TextFormField(
              controller: controller, keyboardType: TextInputType.phone, validator: (val) => val!.isEmpty ? 'Required' : null, cursorColor: _darkGreen,
              decoration: InputDecoration(hintText: 'Phone Number', hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14), border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14)),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFlatDropdown({required String label, required IconData icon, required String? currentValue, required List<String> items, required ValueChanged<String?> onChanged, String? Function(String?)? validator}) {
    return DropdownButtonFormField<String>(
      isExpanded: true, initialValue: currentValue, validator: validator,
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14),
        prefixIcon: Icon(icon, color: Colors.grey.shade500, size: 20),
        filled: true, fillColor: Colors.white,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: Colors.grey.shade300)),
        focusedBorder: const OutlineInputBorder(borderRadius: BorderRadius.zero, borderSide: BorderSide(color: _darkGreen, width: 2)),
      ),
      icon: Icon(Icons.keyboard_arrow_down, color: Colors.grey.shade600),
      dropdownColor: Colors.white,
      items: items.map((item) => DropdownMenuItem(value: item, child: Text(item, style: const TextStyle(fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis))).toList(),
      onChanged: onChanged,
    );
  }
}