import 'package:flutter/material.dart';
import '../../../constant/links.dart';
import '../../../controller/functions/crud.dart';
import '../../widgets/snackbar.dart';

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

  @override
  State<PendingAdminsPage> createState() => _PendingAdminsPageState();
}

class _PendingAdminsPageState extends State<PendingAdminsPage> {
  final CRUD _crud = CRUD();
  bool _isLoading = true;
  List _pendingAdmins = [];

  @override
  void initState() {
    super.initState();
    _fetchPendingAdmins();
  }

  Future<void> _fetchPendingAdmins() async {
    setState(() => _isLoading = true);
    try {
      final response = await _crud.post(
        link: '${AppLink.server}/Admin/auth/list_pending.php',
      );
      if (response != 'failure') {
        setState(() {
          _pendingAdmins = response['message'] ?? [];
        });
      }
    } catch (e) {
      mySnackeBarError('فشل في جلب البيانات: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _handleAction(String adminId, String action) async {
    try {
      final response = await _crud.post(
        link: '${AppLink.server}/Admin/auth/approve_admin.php',
        payload: {
          'admin_id': adminId,
          'action': action,
        },
      );
      if (response != 'failure') {
        mySnackbarSuccess('تم تنفيذ الإجراء بنجاح');
        _fetchPendingAdmins(); // تحديث القائمة
      }
    } catch (e) {
      mySnackeBarError('حدث خطأ: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0D14),
      appBar: AppBar(
        title: const Text('طلبات الانضمام المعلقة', style: TextStyle(fontWeight: FontWeight.bold)),
        backgroundColor: const Color(0xFF161D2E),
        elevation: 0,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator(color: Color(0xFF00E5FF)))
          : _pendingAdmins.isEmpty
              ? _buildEmptyState()
              : _buildList(),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.person_search_rounded, size: 80, color: Colors.grey[800]),
          const SizedBox(height: 16),
          const Text('لا توجد طلبات معلقة حالياً', style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }

  Widget _buildList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _pendingAdmins.length,
      itemBuilder: (context, index) {
        final admin = _pendingAdmins[index];
        return Container(
          margin: const EdgeInsets.only(bottom: 16),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: const Color(0xFF161D2E),
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: const Color(0xFF1F2D4A)),
          ),
          child: Column(
            children: [
              ListTile(
                contentPadding: EdgeInsets.zero,
                leading: const CircleAvatar(
                  backgroundColor: Color(0xFF1F2D4A),
                  child: Icon(Icons.person, color: Color(0xFF00E5FF)),
                ),
                title: Text(admin['name'] ?? 'بدون اسم', style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                subtitle: Text(admin['phone'] ?? 'بدون رقم', style: const TextStyle(color: Colors.grey)),
                trailing: Text(
                  admin['created_at']?.split(' ')[0] ?? '',
                  style: const TextStyle(color: Colors.grey, fontSize: 12),
                ),
              ),
              const Divider(color: Color(0xFF1F2D4A), height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => _handleAction(admin['id'], 'rejected'),
                    style: TextButton.styleFrom(foregroundColor: Colors.redAccent),
                    child: const Text('رفض'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () => _handleAction(admin['id'], 'approved'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF00E5FF),
                      foregroundColor: Colors.black,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                    child: const Text('موافقة', style: TextStyle(fontWeight: FontWeight.bold)),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}
