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

import 'package:flutter/material.dart';
import '../../../../../core/networks/api_client.dart';
import 'add_admin_sub_tab.dart'; 

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

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

  @override
  State<AdminDirectorySubTab> createState() => _AdminDirectorySubTabState();
}

class _AdminDirectorySubTabState extends State<AdminDirectorySubTab> {
  final ScrollController _horizontalScrollController = ScrollController();
  List<Map<String, dynamic>> _existingAdmins = [];
  
  bool _isFetchingAdmins = true;
  bool _isOpeningDialog = false;

  @override
  void initState() {
    super.initState();
    ApiClient.dataChanges.addListener(_onAdminsDataChange);
    _loadAdmins();
  }

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

  Future<void> _loadAdmins({bool refresh = false, bool showLoading = true}) async {
    if (showLoading && _existingAdmins.isEmpty) 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);
        if (showLoading) _showSnackBar('Failed to load administrators.', Colors.redAccent);
      }
    }
  }

  @override
  void dispose() {
    ApiClient.dataChanges.removeListener(_onAdminsDataChange);
    _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),
      ),
    );
  }

  void _confirmDelete(Map<String, dynamic> adminData) {
    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 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.'),
            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.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 _openAddAdminDialog() 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 AddAdminDialog(),
    );
    if (result == true) _loadAdmins();
  }

  void _openEditAdminDialog(Map<String, dynamic> adminData) async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => AddAdminDialog(adminToEdit: adminData),
    );
    if (result == true) _loadAdmins();
  }

  @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('ADMINISTRATOR DIRECTORY', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: Colors.grey.shade800, letterSpacing: 1.5)),
                  const SizedBox(width: 16),
                  if (_isFetchingAdmins) const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen)),
                ],
              ),
              Tooltip(
                message: 'Refresh administrators',
                child: IconButton(
                  onPressed: _isFetchingAdmins ? null : () => _loadAdmins(refresh: true),
                  icon: _isFetchingAdmins
                      ? 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 : _openAddAdminDialog,
                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 ADMIN', 
                  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: _existingAdmins.isEmpty && !_isFetchingAdmins
                ? const Center(child: Text("No administrators found.", 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('NAME')),
                                DataColumn(label: Text('EMAIL')),
                                DataColumn(label: Text('POSITION')),
                                DataColumn(label: Text('ROLE')),
                                DataColumn(label: Text('CAMPUS')),
                                DataColumn(label: Text('ACTIONS')),
                              ],
                              rows: _existingAdmins.map((admin) {
                                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: 10, vertical: 4),
                                        decoration: BoxDecoration(
                                          color: admin['role'] == 'Super Admin' ? _standardGold.withOpacity(0.1) : _darkGreen.withOpacity(0.05),
                                          border: Border.all(color: admin['role'] == 'Super Admin' ? _standardGold : _darkGreen),
                                          borderRadius: BorderRadius.zero,
                                        ),
                                        child: Text(
                                          admin['role'] ?? 'Admin', 
                                          style: TextStyle(
                                            fontSize: 11, 
                                            fontWeight: FontWeight.bold, 
                                            color: admin['role'] == 'Super Admin' ? _standardGold : _darkGreen
                                          )
                                        ),
                                      )
                                    ),
                                    DataCell(Text(admin['campus'] ?? 'Unassigned', style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600))),
                                    DataCell(
                                      Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: const Icon(Icons.edit_outlined, size: 18, color: Colors.blueAccent), 
                                            onPressed: () => _openEditAdminDialog(admin), 
                                            splashRadius: 20
                                          ),
                                          IconButton(
                                            icon: const Icon(Icons.delete_outline, size: 18, color: Colors.redAccent), 
                                            onPressed: () => _confirmDelete(admin), 
                                            splashRadius: 20
                                          ),
                                        ],
                                      )
                                    ),
                                  ],
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      );
                    }
                  ),
            ),
          ),
        ],
      ),
    );
  }
}