// lib/features/admin/tabs/positions/admin_add_admins_tab.dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;

import '../../../../core/constants/app_colors.dart';
import '../../../../core/networks/api_client.dart';

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

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 AdminAddAdminsTab extends StatefulWidget {
  const AdminAddAdminsTab({super.key});

  @override
  State<AdminAddAdminsTab> createState() => _AdminAddAdminsTabState();
}

class _AdminAddAdminsTabState extends State<AdminAddAdminsTab> {
  // Standard Color Palette
  static const Color _standardGold = Color.fromARGB(255, 7, 175, 83);
  static const Color _darkGreen = Color.fromARGB(255, 3, 163, 75); 

  final _formKey = GlobalKey<FormState>();
  final ImagePicker _picker = ImagePicker();
  
  // Existing Controllers
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  
  // New Controllers to match User Table
  final TextEditingController _nrcController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _programController = TextEditingController();
  final ScrollController _horizontalScrollController = ScrollController();
  
  // State Variables
  Uint8List? _profileImageBytes;
  String _selectedRole = 'Moderator';
  String _selectedGender = 'Male';
  bool _isObscured = true;
  bool _isLoading = false;
  bool _isFetchingAdmins = true;

  // Predefined Lists
  final List<String> _roles = ['Super Admin', 'Admin', 'Moderator', 'Content Editor'];
  final List<String> _genderOptions = ['Male', 'Female', 'Other'];
  
  String _selectedCountry = 'Zambia';
  String _selectedCountryCode = '+260';
  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 LISTS
  bool _isFetchingDropdowns = true;
  List<String> _dbCampuses = [];
  List<String> _dbSchools = [];
  List<String> _dbPositions = [];

  String? _selectedCampus;
  String? _selectedSchool;
  String? _selectedPosition;
  
  List<Map<String, dynamic>> _existingAdmins = [];

  @override
  void initState() {
    super.initState();
    _fetchDatabaseDropdowns();
    _loadAdmins();
  }

  Future<void> _fetchDatabaseDropdowns() async {
    if (!mounted) return;
    setState(() => _isFetchingDropdowns = true);
    try {
      final responses = await Future.wait<List<dynamic>>([
        ApiClient.getCampuses(),
        ApiClient.getSchools(),
        ApiClient.getPositions(),
      ]);

      String label(dynamic row, List<String> keys) {
        if (row is! Map) return '';
        for (final key in keys) {
          final value = row[key]?.toString().trim() ?? '';
          if (value.isNotEmpty && value.toLowerCase() != 'null') return value;
        }
        return '';
      }

      if (!mounted) return;
      setState(() {
        _dbCampuses = responses[0].map((row) => label(row, const ['name']))
            .where((value) => value.isNotEmpty).toSet().toList();
        _dbSchools = responses[1].map((row) => label(row, const ['name']))
            .where((value) => value.isNotEmpty).toSet().toList();
        _dbPositions = responses[2]
            .map((row) => label(row, const ['title', 'name', 'position_name']))
            .where((value) => value.isNotEmpty).toSet().toList();
        _isFetchingDropdowns = false;
      });
    } catch (error) {
      if (mounted) {
        setState(() => _isFetchingDropdowns = false);
        _showSnackBar('Could not load current campus, school, and position options: $error', Colors.redAccent);
      }
    }
  }

  Future<void> _loadAdmins({bool refresh = false}) async {
    setState(() => _isFetchingAdmins = true);
    try {
      final admins = await ApiClient.getAdmins(refresh: refresh);
      if (mounted) {
        setState(() {
         _existingAdmins = List<Map<String, dynamic>>.from(admins);
         _isFetchingAdmins = false;
       });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isFetchingAdmins = false);
        _showSnackBar('Failed to load administrators.', Colors.redAccent);
      }
    }
  }

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

  // =====================================================================
  // IMAGE PICKER
  // =====================================================================
  Future<void> _pickImage({void Function(Uint8List)? onPicked}) async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 50, 
      );
      
      if (pickedFile != null) {
        final bytes = await pickedFile.readAsBytes(); 
        if (onPicked != null) {
          onPicked(bytes);
        } else {
          setState(() => _profileImageBytes = bytes);
        }
      }
    } catch (e) {
      debugPrint("Error picking image: $e");
      if (mounted) _showSnackBar('Failed to pick image.', Colors.redAccent);
    }
  }

  // =====================================================================
  // ACTIONS: ADD, EDIT, DELETE
  // =====================================================================
  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      if (_selectedCampus == null || _selectedSchool == null) {
        _showSnackBar('Please select a Campus and School.', Colors.redAccent);
        return;
      }
      if (_selectedPosition == null) {
        _showSnackBar('Please assign an official position.', Colors.redAccent);
        return;
      }

      setState(() => _isLoading = true);

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

        String base64Image = '';
        if (_profileImageBytes != null) base64Image = base64Encode(_profileImageBytes!);

        final adminData = {
          'name': _nameController.text.trim(),
          'email': _emailController.text.trim(),
          'role': _selectedRole,
          'position': _selectedPosition,
          'campus': _selectedCampus,
          'password': safePassword,
        };

        final bool adminSuccess = await ApiClient.addAdmin(adminData);

        if (adminSuccess && mounted) {
          
          // SYNCHRONIZE WITH USERS TABLE
          try {
            final userPayload = {
              'full_name': _nameController.text.trim(),
              'email': _emailController.text.trim(),
              'password': safePassword,
              'nrc': _nrcController.text.trim(),
              'phone': "$_selectedCountryCode ${_phoneController.text.trim()}",
              'gender': _selectedGender,
              'country': _selectedCountry,
              'campus': _selectedCampus,
              'school': _selectedSchool,
              'program': _programController.text.trim(),
              'role': _selectedRole, 
              'position': _selectedPosition, // 🚀 Sync position to companion user
              'profile_picture': base64Image,
            };
            
            await http.post(
              Uri.parse('${ApiClient.baseUrl}/users'),
              headers: {'Content-Type': 'application/json'},
              body: jsonEncode(userPayload)
            );

            // --- INSTANT ISAR LOCAL DATABASE SYNC ---
            final newLocalUser = UserModel()
              ..fullName = _nameController.text.trim()
              ..role = _selectedRole
              ..campus = _selectedCampus
              ..school = _selectedSchool
              ..program = _programController.text.trim()
              ..email = _emailController.text.trim()
              ..profilePicture = base64Image;

            await isarDB.writeTxn(() async {
              await isarDB.userModels.put(newLocalUser); 
            });

          } catch (e) {
            debugPrint("Companion user account creation failed: $e");
          }

          _showSnackBar('Administrator added successfully to both portals.', const Color.fromARGB(255, 4, 138, 64));
          
          _nameController.clear();
          _emailController.clear();
          _passwordController.clear();
          _nrcController.clear();
          _phoneController.clear();
          _programController.clear();
          setState(() {
            _profileImageBytes = null;
            _selectedCampus = null;
            _selectedSchool = null;
            _selectedPosition = null;
          });
          
          await _loadAdmins();
        } else {
          throw Exception("Server returned false");
        }
      } catch (e) {
        if (mounted) _showSnackBar('Failed to add administrator to the system.', Colors.redAccent);
      } finally {
        if (mounted) setState(() => _isLoading = false);
      }
    }
  }

  void _showEditDialog(Map<String, dynamic> adminData) {
    final editFormKey = GlobalKey<FormState>();
    final editNameCtrl = TextEditingController(text: adminData['name']);
    final editEmailCtrl = TextEditingController(text: adminData['email']);
    
    String editSelectedRole = adminData['role'] ?? 'Moderator';
    String? editSelectedPosition = adminData['position'];
    
    if (editSelectedPosition != null && !_dbPositions.contains(editSelectedPosition)) {
      _dbPositions.add(editSelectedPosition);
    }
    
    bool isUpdating = false;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), 
            backgroundColor: Colors.white,
            title: const Text('Edit Administrator', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
            content: SizedBox(
              width: MediaQuery.sizeOf(context).width < 600 ? MediaQuery.sizeOf(context).width - 72 : 500,
              child: Form(
                key: editFormKey,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildFlatTextField(
                        controller: editNameCtrl,
                        label: 'Full Name',
                        icon: Icons.person_outline,
                        validator: (value) => value!.isEmpty ? 'Name is required' : null,
                      ),
                      const SizedBox(height: 16),
                      _buildFlatTextField(
                        controller: editEmailCtrl,
                        label: 'Official Email',
                        icon: Icons.email_outlined,
                        keyboardType: TextInputType.emailAddress,
                        validator: (value) => value!.contains('@') ? null : 'Enter a valid email',
                      ),
                      const SizedBox(height: 16),
                      _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                              label: 'Role',
                              icon: Icons.shield_outlined,
                              currentValue: editSelectedRole,
                              items: _roles,
                              onChanged: (value) {
                                if (value != null) setDialogState(() => editSelectedRole = value);
                              },
                            ),
            _buildFlatDropdown(
                              label: 'Position',
                              icon: Icons.work_outline,
                              currentValue: editSelectedPosition,
                              items: _dbPositions,
                              onChanged: (value) => setDialogState(() => editSelectedPosition = value),
                              validator: (val) => val == null ? 'Required' : null,
                            ),
          ]),
                    ],
                  ),
                ),
              ),
            ),
            actionsPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
            actions: [
              TextButton(
                onPressed: isUpdating ? null : () => Navigator.pop(ctx),
                child: Text('CANCEL', style: TextStyle(color: Colors.grey.shade600, fontWeight: FontWeight.bold)),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: _darkGreen,
                  foregroundColor: Colors.white,
                  elevation: 0,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
                ),
                onPressed: isUpdating ? null : () async {
                  if (editFormKey.currentState!.validate()) {
                    setDialogState(() => isUpdating = true);
                    
                    final updatePayload = {
                      'name': editNameCtrl.text.trim(),
                      'email': editEmailCtrl.text.trim(),
                      'role': editSelectedRole,
                      'position': editSelectedPosition,
                    };

                    final success = await ApiClient.updateAdmin(adminData['id'], updatePayload);
                    
                    if (success && mounted) {
                      Navigator.pop(ctx);
                      _showSnackBar('Administrator updated successfully.', _darkGreen);
                      _loadAdmins(); 
                    } else {
                      setDialogState(() => isUpdating = false);
                      _showSnackBar('Update failed.', Colors.redAccent);
                    }
                  }
                },
                child: isUpdating 
                  ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                  : const Text('SAVE CHANGES'),
              ),
            ],
          );
        }
      ),
    );
  }

  void _confirmDelete(Map<String, dynamic> adminData) {
    bool isDeleting = false;
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
            backgroundColor: Colors.white,
            title: Row(
              children: [
                const Icon(Icons.warning_amber_rounded, color: Colors.redAccent),
                const SizedBox(width: 8),
                const Text('Remove Admin', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
              ],
            ),
            content: Text(
              'Are you sure you want to revoke access for ${adminData['name']}? This action cannot be undone.',
              style: TextStyle(color: Colors.grey.shade800),
            ),
            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: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
                ),
                onPressed: isDeleting ? null : () async {
                  setDialogState(() => isDeleting = true);
                  final success = await ApiClient.deleteAdmin(adminData['id']);
                  
                  if (success && mounted) {
                    Navigator.pop(ctx);
                    _showSnackBar('${adminData['name']} has been removed.', Colors.black87);
                    _loadAdmins(); 
                  } else {
                    setDialogState(() => isDeleting = false);
                    _showSnackBar('Failed to delete admin.', Colors.redAccent);
                  }
                },
                child: isDeleting 
                  ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                  : const Text('DELETE'),
              ),
            ],
          );
        }
      ),
    );
  }

  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: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
      ),
    );
  }

  // =====================================================================
  // MAIN BUILD
  // =====================================================================
  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.sizeOf(context).width;
    final isDesktop = screenWidth > 1200;

    return SingleChildScrollView(
      padding: EdgeInsets.all(screenWidth < 600 ? 12.0 : 32.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Administrator Management',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black87),
          ),
          const SizedBox(height: 8),
          Text(
            'Provision new admin accounts and manage existing dashboard access.',
            style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
          ),
          const SizedBox(height: 32),
          
          if (isDesktop)
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(flex: 4, child: _buildAddAdminForm()),
                const SizedBox(width: 32),
                Expanded(flex: 7, child: _buildAdminsTable()),
              ],
            )
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildAddAdminForm(),
                const SizedBox(height: 32),
                _buildAdminsTable(),
              ],
            ),
        ],
      ),
    );
  }

  // =====================================================================
  // ADD ADMIN FORM (FLAT UI)
  // =====================================================================
  Widget _buildAddAdminForm() {
    return Container(
      padding: EdgeInsets.all(MediaQuery.sizeOf(context).width < 600 ? 16 : 24),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey.shade300, width: 1), 
        borderRadius: BorderRadius.circular(4), 
      ),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.only(bottom: 12),
              decoration: const BoxDecoration(
                border: Border(bottom: BorderSide(color: _standardGold, width: 2))
              ),
              child: const Text('Provision New Account', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            ),
            const SizedBox(height: 24),
            
            Center(
              child: GestureDetector(
                onTap: _pickImage,
                child: Stack(
                  alignment: Alignment.bottomRight,
                  children: [
                    Container(
                      width: 90, height: 90,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade100,
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.grey.shade300, width: 1),
                      ),
                      clipBehavior: Clip.hardEdge,
                      child: _profileImageBytes != null 
                          ? Image.memory(_profileImageBytes!, fit: BoxFit.cover)
                          : Icon(Icons.person, size: 45, color: Colors.grey.shade400),
                    ),
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: const BoxDecoration(color: _darkGreen, shape: BoxShape.circle),
                      child: const Icon(Icons.camera_alt, color: Colors.white, size: 16),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),

            _buildFlatTextField(
              controller: _nameController,
              label: 'Full Name',
              icon: Icons.person_outline,
              validator: (value) => value!.isEmpty ? 'Name is required' : null,
            ),
            const SizedBox(height: 16),
            
            _buildFlatTextField(
              controller: _emailController,
              label: 'Official Email',
              icon: Icons.email_outlined,
              keyboardType: TextInputType.emailAddress,
              validator: (value) => value!.contains('@') ? null : 'Enter a valid email',
            ),
            const SizedBox(height: 16),

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

            _buildFlatPhoneInput(
              controller: _phoneController, currentCode: _selectedCountryCode,
              onCodeChanged: (String? newValue) {
                if (newValue != null) {
                  setState(() {
                    _selectedCountryCode = newValue;
                    _selectedCountry = _countries.firstWhere((c) => c['code'] == newValue)['name']!;
                  });
                }
              },
            ),
            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("Syncing DB...", style: TextStyle(fontWeight: FontWeight.bold, color: _darkGreen))])
                  )
                : Column(
                    children: [
                      _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                              label: 'Campus', icon: Icons.domain, currentValue: _selectedCampus, items: _dbCampuses,
                              onChanged: (value) => setState(() => _selectedCampus = value), validator: (val) => val == null ? 'Required' : null,
                            ),
            _buildFlatDropdown(
                              label: 'School', icon: Icons.account_balance, currentValue: _selectedSchool, items: _dbSchools,
                              onChanged: (value) => setState(() => _selectedSchool = value), validator: (val) => val == null ? 'Required' : null,
                            ),
          ]),
                      const SizedBox(height: 16),
                      _buildFlatTextField(controller: _programController, label: 'Program / Department', icon: Icons.book_outlined),
                      const SizedBox(height: 16),
                      _responsiveAdminFormFields(context, [
            _buildFlatDropdown(
                              label: 'Role', icon: Icons.shield_outlined, currentValue: _selectedRole, items: _roles,
                              onChanged: (value) { if (value != null) setState(() => _selectedRole = value); }
                            ),
            _buildFlatDropdown(
                              label: 'Position', icon: Icons.work_outline, currentValue: _selectedPosition, items: _dbPositions,
                              onChanged: (value) => setState(() => _selectedPosition = value), validator: (val) => val == null ? 'Required' : null,
                            ),
          ]),
                    ],
                  ),
            
            const SizedBox(height: 16),
            
            _buildFlatTextField(
              controller: _passwordController, 
              label: 'Temporary Password', 
              icon: Icons.lock_outline, 
              isPassword: true,
              validator: (value) => value!.length < 6 ? 'Minimum 6 characters' : null,
            ),
            const SizedBox(height: 32),
            
            SizedBox(
              width: double.infinity,
              height: 48,
              child: ElevatedButton(
                onPressed: _isLoading ? null : _submitForm,
                style: ElevatedButton.styleFrom(
                  backgroundColor: _darkGreen, foregroundColor: Colors.white, elevation: 0, 
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
                  side: const BorderSide(color: _darkGreen, width: 1),
                ),
                child: _isLoading
                    ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                    : const Text('CREATE ACCOUNT', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.0)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // =====================================================================
  // EXISTING ADMINS TABLE (FLAT UI)
  // =====================================================================
  Widget _buildAdminsTable() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey.shade300, width: 1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              border: Border(bottom: BorderSide(color: Colors.grey.shade300, width: 1)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Active Administrators', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                if (_isFetchingAdmins)
                  const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
                else
                  Icon(Icons.admin_panel_settings_outlined, color: Colors.grey.shade600),
              ],
            ),
          ),
          
          if (_existingAdmins.isEmpty && !_isFetchingAdmins)
             const Padding(
               padding: EdgeInsets.all(32.0),
               child: Center(child: Text("No administrators found.")),
             )
          else
            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.all(Colors.white),
                        dataRowColor: WidgetStateProperty.resolveWith((states) {
                          if (states.contains(WidgetState.hovered)) return Colors.grey.shade50;
                          return Colors.white;
                        }),
                        dividerThickness: 1,
                        columns: const [
                          DataColumn(label: Text('NAME', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))),
                          DataColumn(label: Text('EMAIL', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))),
                          DataColumn(label: Text('POSITION', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))), // 🚀 NEW POSITION COLUMN
                          DataColumn(label: Text('ROLE', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))),
                          DataColumn(label: Text('DATE ADDED', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))),
                          DataColumn(label: Text('ACTIONS', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, color: Colors.black54))),
                        ],
                        rows: _existingAdmins.map((admin) {
                          String dateAdded = admin['created_at'] != null 
                              ? admin['created_at'].toString().split('T')[0] 
                              : 'Unknown';
                          
                          return DataRow(
                            cells: [
                              DataCell(Text(admin['name'] ?? '', style: const TextStyle(fontWeight: FontWeight.w600))),
                              DataCell(Text(admin['email'] ?? '', style: TextStyle(color: Colors.grey.shade700))),
                              DataCell(Text(admin['position'] ?? 'Unassigned', style: const TextStyle(fontWeight: FontWeight.bold))), // 🚀 DISPLAY POSITION
                              DataCell(
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  decoration: BoxDecoration(
                                    color: admin['role'] == 'Super Admin' ? _standardGold.withOpacity(0.2) : _darkGreen.withOpacity(0.1),
                                    border: Border.all(color: admin['role'] == 'Super Admin' ? _standardGold : _darkGreen),
                                    borderRadius: BorderRadius.circular(2),
                                  ),
                                  child: Text(
                                    admin['role'] ?? 'Admin', 
                                    style: TextStyle(
                                      fontSize: 11, 
                                      fontWeight: FontWeight.bold, 
                                      color: admin['role'] == 'Super Admin' ? Colors.black87 : _darkGreen
                                    )
                                  ),
                                )
                              ),
                              DataCell(Text(dateAdded, style: TextStyle(color: Colors.grey.shade600))),
                              DataCell(
                                Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.edit_outlined, size: 18, color: Colors.blueAccent), 
                                      onPressed: () => _showEditDialog(admin), 
                                      splashRadius: 20, tooltip: 'Edit Admin',
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.delete_outline, size: 18, color: Colors.redAccent), 
                                      onPressed: () => _confirmDelete(admin), 
                                      splashRadius: 20, tooltip: 'Remove Admin',
                                    ),
                                  ],
                                )
                              ),
                            ],
                          );
                        }).toList(),
                      ),
                    ),
                  ),
                );
              }
            ),
        ],
      ),
    );
  }

  // =====================================================================
  // FLAT CUSTOM 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: _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.grey.shade50,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: BorderSide(color: Colors.grey.shade300)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: BorderSide(color: Colors.grey.shade300)),
        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: const BorderSide(color: _darkGreen, width: 2)),
        errorBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: const 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.circular(4),
        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((country) {
                  return DropdownMenuItem(
                    value: country['code'],
                    child: Text(
                      "${country['flag']} ${country['code']}", 
                      overflow: TextOverflow.ellipsis,
                    ),
                  );
                }).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 ? 'Phone 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.grey.shade50,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: BorderSide(color: Colors.grey.shade300)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: BorderSide(color: Colors.grey.shade300)),
        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: const BorderSide(color: _darkGreen, width: 2)),
        errorBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(4), borderSide: const BorderSide(color: Colors.redAccent)),
      ),
      icon: Icon(Icons.keyboard_arrow_down, color: Colors.grey.shade600),
      dropdownColor: Colors.white,
      items: items.map((item) {
        return DropdownMenuItem(
          value: item,
          child: Text(item, style: const TextStyle(fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
        );
      }).toList(),
      onChanged: onChanged,
    );
  }
}