// lib/features/admin/tabs/positions/add_admin_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';

// --- ISAR IMPORTS ---
import '../../../../main.dart'; 
import '../../../map_search/models/user_model.dart'; 

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

Widget _responsiveAdminFormFields(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 AddAdminDialog extends StatefulWidget {
  final Map<String, dynamic>? adminToEdit;

  const AddAdminDialog({super.key, this.adminToEdit});

  @override
  State<AddAdminDialog> createState() => _AddAdminDialogState();
}

class _AddAdminDialogState extends State<AddAdminDialog> {
  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  
  late TextEditingController _nameController;
  late TextEditingController _emailController;
  late TextEditingController _nrcController;
  late TextEditingController _phoneController;
  late TextEditingController _programController;
  late TextEditingController _passwordController;
  
  Uint8List? _profileImageBytes;
  String? _profileImageName;
  String? _existingProfileImageStr;
  
  String _selectedRole = 'Admin';
  String _selectedGender = 'Male';
  bool _isObscured = true;
  bool _isLoading = false;

  final List<String> _roles = ['Admin', 'Admin0', 'Admin001'];
  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': '🇿🇦'},
  ];

  // --- DYNAMIC DATABASE DROPDOWNS ---
  bool _isFetchingDropdowns = true;
  List<String> _dbCampuses = [];
  List<String> _dbSchools = [];
  List<String> _dbDepartments = [];
  List<String> _dbPositions = [];

  String? _selectedCampus;
  String? _selectedSchool;
  String? _selectedDepartment;
  String? _selectedPosition;
  String? _dropdownError;

  @override
  void initState() {
    super.initState();
    
    // Initialize controllers from the administrator record when editing.
    // The backend returns companion profile fields (NRC, phone, school, program,
    // profile picture) together with the administrator row, so keep them intact.
    final edit = widget.adminToEdit;
    _nameController = TextEditingController(text: edit?['name']?.toString() ?? '');
    _emailController = TextEditingController(text: edit?['email']?.toString() ?? '');
    _nrcController = TextEditingController(text: edit?['nrc']?.toString() ?? '');
    _programController = TextEditingController();
    _passwordController = TextEditingController();

    var existingPhone = edit?['phone']?.toString().trim() ?? '';
    for (final country in _countries) {
      final code = country['code'] ?? '';
      if (code.isNotEmpty && existingPhone.startsWith(code)) {
        _selectedCountryCode = code;
        _selectedCountry = country['name'] ?? _selectedCountry;
        existingPhone = existingPhone.substring(code.length).trim();
        break;
      }
    }
    _phoneController = TextEditingController(text: existingPhone);
    _existingProfileImageStr = edit?['profile_picture']?.toString();

    if (edit != null) {
      if (_roles.contains(edit['role'])) {
        _selectedRole = edit['role'];
      }
      final gender = edit['gender']?.toString();
      if (gender != null && _genderOptions.contains(gender)) {
        _selectedGender = gender;
      }
      final country = edit['country']?.toString().trim();
      if (country != null && country.isNotEmpty) {
        _selectedCountry = country;
      }
      _selectedPosition = edit['position']?.toString();
      _selectedCampus = edit['campus']?.toString();
      _selectedSchool = edit['school']?.toString();

      // Rockview currently stores a staff/admin department name in users.program.
      // Prefer an explicit department field if one exists, otherwise use program.
      _selectedDepartment = (edit['department'] ?? edit['program'])?.toString();
    }

    _fetchDatabaseDropdowns();
  }

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

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

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

      final campuses = _extractDatabaseLabels(results[0], const ['name']);
      final schools = _extractDatabaseLabels(results[1], const ['name']);
      final departments = _extractDatabaseLabels(results[2], const ['name']);
      final positions = _extractDatabaseLabels(
        results[3],
        const ['title', 'name', 'position_name'],
      );

      if (!mounted) return;
      setState(() {
        _dbCampuses = campuses;
        _dbSchools = schools;
        _dbDepartments = departments;
        _dbPositions = positions;

        _selectedCampus = _validatedSelection(_selectedCampus, _dbCampuses);
        _selectedSchool = _validatedSelection(_selectedSchool, _dbSchools);
        _selectedDepartment = _validatedSelection(_selectedDepartment, _dbDepartments);
        _selectedPosition = _validatedSelection(_selectedPosition, _dbPositions);

        final missing = <String>[];
        if (_dbCampuses.isEmpty) missing.add('campuses');
        if (_dbSchools.isEmpty) missing.add('schools');
        if (_dbDepartments.isEmpty) missing.add('departments');
        if (_dbPositions.isEmpty) missing.add('positions');
        if (missing.isNotEmpty) {
          _dropdownError = 'No ${missing.join(', ')} were returned by the database. Register them first or check the related API endpoint.';
        }
        _isFetchingDropdowns = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _dbCampuses = [];
        _dbSchools = [];
        _dbDepartments = [];
        _dbPositions = [];
        _dropdownError = 'Unable to synchronize institutional records from the database: $e';
        _isFetchingDropdowns = false;
      });
    }
  }

  List<String> _extractDatabaseLabels(List<dynamic> rows, List<String> keys) {
    final values = <String>[];
    final seen = <String>{};

    for (final row in rows) {
      if (row is! Map) continue;
      String value = '';
      for (final key in keys) {
        final candidate = row[key]?.toString().trim() ?? '';
        if (candidate.isNotEmpty && candidate.toLowerCase() != 'null') {
          value = candidate;
          break;
        }
      }
      if (value.isNotEmpty && seen.add(value.toLowerCase())) values.add(value);
    }

    values.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return values;
  }

  String? _validatedSelection(String? value, List<String> items) {
    final clean = value?.trim();
    if (clean == null || clean.isEmpty) return null;
    for (final item in items) {
      if (item.toLowerCase() == clean.toLowerCase()) return item;
    }
    return null;
  }

  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;
          _profileImageName = pickedFile.name;
        });
      }
    } 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);
    }

    final value = _existingProfileImageStr?.trim() ?? '';
    if (value.isEmpty) {
      return Icon(Icons.person_rounded, size: 55, color: Colors.grey.shade400);
    }

    if (value.startsWith('http://') ||
        value.startsWith('https://') ||
        ApiClient.isStoredProfilePicturePath(value)) {
      return Image.network(
        ApiClient.resolveMediaUrl(value),
        fit: BoxFit.cover,
        width: 140,
        height: 140,
        errorBuilder: (_, _, _) =>
            Icon(Icons.person_rounded, size: 55, color: Colors.grey.shade400),
      );
    }

    // Backward compatibility for old Base64 profile values.
    try {
      final payload = value.startsWith('data:image') && value.contains(',')
          ? value.substring(value.indexOf(',') + 1)
          : value;
      return Image.memory(
        base64Decode(payload),
        fit: BoxFit.cover,
        width: 140,
        height: 140,
      );
    } catch (_) {
      return Icon(Icons.person_rounded, size: 55, color: Colors.grey.shade400);
    }
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      if (_isFetchingDropdowns) {
        _showSnackBar('Institutional records are still loading. Please try again.', Colors.redAccent);
        return;
      }
      if (_dropdownError != null) {
        _showSnackBar(_dropdownError!, Colors.redAccent);
        return;
      }
      if (_selectedPosition == null) {
        _showSnackBar('Please assign an official position from the database.', Colors.redAccent);
        return;
      }
      // Campus is required for BOTH new and existing administrators because
      // request routing depends on the administrator's current campus.
      if (_selectedCampus == null || _selectedCampus!.trim().isEmpty) {
        _showSnackBar('Please select the administrator campus.', Colors.redAccent);
        return;
      }

      // School and department are companion-profile requirements during
      // initial provisioning. Campus remains independently editable later.
      if (widget.adminToEdit == null &&
          (_selectedSchool == null || _selectedDepartment == null)) {
        _showSnackBar('Please select a School and Department for the companion profile.', Colors.redAccent);
        return;
      }
      if (widget.adminToEdit == null && _nrcController.text.trim().isEmpty) {
        _showSnackBar('NRC / ID Number is required for a new administrator.', Colors.redAccent);
        return;
      }
      if (widget.adminToEdit == null && _phoneController.text.trim().isEmpty) {
        _showSnackBar('Phone number is required for a new administrator.', Colors.redAccent);
        return;
      }
      if (widget.adminToEdit == null && _passwordController.text.trim().isEmpty) {
        _showSnackBar('Initial password is required for new accounts.', Colors.redAccent);
        return;
      }

      setState(() => _isLoading = true);

      String? uploadedNewPath;
      try {
        String safePassword = _passwordController.text;
        if (safePassword.length > 72) safePassword = safePassword.substring(0, 72);

        String profileImageValue = _existingProfileImageStr?.trim() ?? '';
        if (_profileImageBytes != null) {
          uploadedNewPath = await ApiClient.uploadProfilePicture(
            _profileImageBytes!,
            fileName: _profileImageName ?? 'admin_profile.jpg',
          );
          profileImageValue = uploadedNewPath;
        }

        bool success = false;

        if (widget.adminToEdit == null) {
          // CREATE NEW ADMIN + COMPANION USER IN ONE BACKEND TRANSACTION.
          // admin.php already creates/synchronizes the matching users row, so
          // every required profile value must be sent in this first request.
          final nrc = _nrcController.text.trim();
          final phone = _phoneController.text.trim();

          final Map<String, dynamic> adminData = {
            'name': _nameController.text.trim(),
            'full_name': _nameController.text.trim(),
            'email': _emailController.text.trim(),
            'password': safePassword,
            'nrc': nrc,
            'phone': '$_selectedCountryCode $phone',
            'gender': _selectedGender,
            'country': _selectedCountry,
            'role': _selectedRole,
            'position': _selectedPosition,
            'campus': _selectedCampus,
            'school': _selectedSchool,
            // Current Rockview users schema stores the department name in program.
            'program': _selectedDepartment,
            'profile_picture': profileImageValue,
          };

          success = await ApiClient.addAdmin(adminData);

          if (success) {
            // Local Isar is only a cache. A cache failure must never create a
            // second PostgreSQL user or roll back the successful backend record.
            try {
              final newLocalUser = UserModel()
                ..fullName = _nameController.text.trim()
                ..role = _selectedRole
                ..campus = _selectedCampus
                ..school = _selectedSchool
                ..program = _selectedDepartment
                ..email = _emailController.text.trim()
                ..profilePicture = _profileImageBytes != null
                    ? base64Encode(_profileImageBytes!)
                    : profileImageValue;

              await isarDB.writeTxn(() async {
                await isarDB.userModels.put(newLocalUser);
              });
            } catch (localError) {
              debugPrint('Local administrator cache sync failed: $localError');
            }
          }
        } else {
          // UPDATE EXISTING ADMIN. Never send a blank password. Profile fields
          // are included only when they are already available, so the backend
          // preserves existing companion data rather than replacing it with null.
          final Map<String, dynamic> adminData = {
            'name': _nameController.text.trim(),
            'email': _emailController.text.trim(),
            'role': _selectedRole,
            'position': _selectedPosition,
            'campus': _selectedCampus,
          };

          final nrc = _nrcController.text.trim();
          final phone = _phoneController.text.trim();
          if (nrc.isNotEmpty) adminData['nrc'] = nrc;
          if (phone.isNotEmpty) adminData['phone'] = '$_selectedCountryCode $phone';
          if (_selectedGender.trim().isNotEmpty) adminData['gender'] = _selectedGender;
          if (_selectedCountry.trim().isNotEmpty) adminData['country'] = _selectedCountry;
          if (_selectedSchool != null) adminData['school'] = _selectedSchool;
          if (_selectedDepartment != null) adminData['program'] = _selectedDepartment;
          if (profileImageValue.isNotEmpty) adminData['profile_picture'] = profileImageValue;
          if (safePassword.trim().isNotEmpty) adminData['password'] = safePassword;

          success = await ApiClient.updateAdmin(widget.adminToEdit!['id'], adminData);
        }

        if (success && mounted) {
          _showSnackBar(widget.adminToEdit == null ? 'Administrator provisioned successfully.' : 'Administrator updated successfully.', _darkGreen);
          Navigator.pop(context, true); 
        } else {
          throw Exception("Server returned false");
        }
      } catch (e) {
        if (uploadedNewPath != null) {
          try {
            await ApiClient.deleteProfilePicture(uploadedNewPath);
          } catch (cleanupError) {
            debugPrint('Uploaded admin profile cleanup warning: $cleanupError');
          }
        }
        if (mounted) {
          _showSnackBar('Failed to save administrator record: $e', Colors.redAccent);
        }
      } finally {
        if (mounted) setState(() => _isLoading = false);
      }
    }
  }

  void _showSnackBar(String message, Color color) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.info_outline, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(child: 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.adminToEdit != 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 : 850, maxHeight: MediaQuery.sizeOf(context).height * 0.9),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // --- HEADER SECTION ---
            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 ADMINISTRATOR' : 'PROVISION NEW ADMIN', 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(),
                  ),
                ],
              ),
            ),
            
            // --- SCROLLABLE FORM CONTENT ---
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 16 : 48),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // --- CIRCULAR AVATAR PICKER (Only on creation) ---
                      if (!isEditing) ...[
                        Center(
                          child: GestureDetector(
                            onTap: _pickImage,
                            child: Stack(
                              alignment: Alignment.bottomRight,
                              children: [
                                Container(
                                  width: 140, height: 140,
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade50,
                                    shape: BoxShape.circle, 
                                    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(
                                    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)),
                                            ],
                                          ),
                                  ),
                                ),
                                Positioned(
                                  bottom: 4, right: 4,
                                  child: Container(
                                    padding: const EdgeInsets.all(10),
                                    decoration: BoxDecoration(
                                      color: _darkGreen, shape: BoxShape.circle,
                                      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),
                      ],

                      // --- SECTION: PERSONAL DETAILS ---
                      _buildSectionTitle('Administrative Information'),
                      const SizedBox(height: 20),

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

                      if (_dropdownError != null && !_isFetchingDropdowns) ...[
                        SelectableText(_dropdownError!, style: const TextStyle(color: Colors.redAccent, fontWeight: FontWeight.w600)),
                        const SizedBox(height: 16),
                      ],

                      _isFetchingDropdowns
                          ? Container(
                              padding: const EdgeInsets.all(16), decoration: BoxDecoration(color: Colors.grey.shade50, border: Border.all(color: Colors.grey.shade200)),
                              child: const Row(mainAxisAlignment: MainAxisAlignment.center, children: [SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)), SizedBox(width: 16), Text("Synchronizing Roles & Positions...", style: TextStyle(fontWeight: FontWeight.bold, color: _darkGreen))]),
                            )
                          : _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                                    label: 'Administrator Role', icon: Icons.shield_outlined, currentValue: _selectedRole, items: _roles,
                                    onChanged: (val) { if (val != null) setState(() => _selectedRole = val); }
                                  ),
            _buildFlatDropdown(
                                    label: 'Official Position', icon: Icons.work_outline, currentValue: _selectedPosition, items: _dbPositions,
                                    onChanged: (val) => setState(() => _selectedPosition = val),
                                    validator: (val) => val == null ? 'Position Required' : null,
                                  ),
          ]),

                      // Campus must remain visible when editing an administrator.
                      // Previously it was inside the creation-only companion
                      // profile section, so the EDIT dialog hid it completely.
                      if (isEditing) ...[
                        const SizedBox(height: 16),
                        _buildFlatDropdown(
                          label: 'Campus Allocation',
                          icon: Icons.domain_outlined,
                          currentValue: _selectedCampus,
                          items: _dbCampuses,
                          onChanged: (val) => setState(() => _selectedCampus = val),
                          validator: (val) => val == null ? 'Campus Required' : null,
                        ),
                      ],
                      
                      // --- SECTION: COMPANION PROFILE DETAILS ---
                      if (!isEditing) ...[
                        const SizedBox(height: 40),
                        const Divider(height: 1),
                        const SizedBox(height: 40),

                        _buildSectionTitle('Companion Profile Details'),
                        const SizedBox(height: 20),
                        
                        _responsiveAdminFormFields(context, [
            _buildFlatTextField(controller: _nrcController, label: 'NRC / ID Number', icon: Icons.credit_card_outlined, validator: (v) => (v == null || v.trim().isEmpty) ? 'NRC / ID Number is required' : null),
            _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(24), decoration: BoxDecoration(color: Colors.grey.shade50, border: Border.all(color: Colors.grey.shade200)),
                                child: const Row(mainAxisAlignment: MainAxisAlignment.center, children: [SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)), SizedBox(width: 16), Text("Synchronizing Campuses, Schools & Departments...", style: TextStyle(fontWeight: FontWeight.bold, color: _darkGreen))])
                              )
                            : _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                                      label: 'Campus Allocation', icon: Icons.domain, currentValue: _selectedCampus, items: _dbCampuses,
                                      onChanged: (val) => setState(() => _selectedCampus = val), validator: (val) => val == null ? 'Required' : null,
                                    ),
            _buildFlatDropdown(
                                      label: 'School Assignment', icon: Icons.account_balance, currentValue: _selectedSchool, items: _dbSchools,
                                      onChanged: (val) => setState(() => _selectedSchool = val), validator: (val) => val == null ? 'Required' : null,
                                    ),
          ]),
                        const SizedBox(height: 16),
                        _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                                label: 'Department Assignment', icon: Icons.account_tree_outlined, currentValue: _selectedDepartment, items: _dbDepartments,
                                onChanged: (val) => setState(() => _selectedDepartment = val), validator: (val) => val == null ? 'Required' : null,
                              ),
            _buildFlatTextField(controller: _programController, label: 'Program / Scope', icon: Icons.book_outlined),
          ]),
                      ],
                      
                      const SizedBox(height: 40),
                      const Divider(height: 1),
                      const SizedBox(height: 40),

                      // --- SECTION: SECURITY ---
                      _buildSectionTitle('Security & Authentication'),
                      const SizedBox(height: 20),
                      
                      _buildFlatTextField(
                        controller: _passwordController, 
                        label: isEditing ? 'Change Password (Leave blank to keep current)' : 'Initial Login Password', 
                        icon: Icons.lock_outline, 
                        isPassword: true,
                        validator: (v) {
                          if (isEditing && v!.isEmpty) return null;
                          if (v!.isNotEmpty && v.length < 6) return 'Minimum 6 characters required';
                          return null;
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // --- FOOTER ACTION BUTTONS ---
            Container(
              padding: EdgeInsets.symmetric(horizontal: compact ? 12 : 32, vertical: 16),
              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)),
                  ),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _submitForm,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _darkGreen, foregroundColor: Colors.white, elevation: 0,
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 20),
                    ),
                    child: _isLoading 
                        ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Icon(Icons.check_circle_outline_rounded, size: 20, color: Colors.white),
                              const SizedBox(width: 12),
                              Text(
                                isEditing ? 'UPDATE RECORD' : 'PROVISION ADMIN',
                                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0),
                              ),
                            ],
                          ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // --- FLAT INPUT WIDGETS ---
  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: _standardGold,
      style: const TextStyle(fontWeight: FontWeight.w600),
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14, fontWeight: FontWeight.normal),
        prefixIcon: Icon(icon, color: _standardGold, size: 22),
        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.grey.shade50, 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: _standardGold, 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.grey.shade50, borderRadius: BorderRadius.zero, border: Border.all(color: Colors.grey.shade300)),
      child: Row(
        children: [
          const Padding(padding: EdgeInsets.only(left: 16.0), child: Icon(Icons.phone_outlined, color: _standardGold, size: 22)),
          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.w600), 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: _standardGold, style: const TextStyle(fontWeight: FontWeight.w600), decoration: InputDecoration(hintText: 'Phone Number', hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14, fontWeight: FontWeight.normal), 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, value: currentValue, validator: validator,
      style: const TextStyle(fontWeight: FontWeight.w600, color: Colors.black87, fontSize: 14),
      decoration: InputDecoration(
        labelText: label, labelStyle: TextStyle(color: Colors.grey.shade600, fontSize: 14, fontWeight: FontWeight.normal), prefixIcon: Icon(icon, color: _standardGold, size: 22),
        filled: true, fillColor: Colors.grey.shade50, 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: _standardGold, 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, overflow: TextOverflow.ellipsis))).toList(),
      onChanged: onChanged,
    );
  }
}