import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/super_admin_stats_model.dart';
import '../cubit/dashboard_cubit.dart';

class SuperAdminView extends StatelessWidget {
  final SuperAdminStatsModel? stats;

  const SuperAdminView({
    super.key,
    required this.stats,
  });

  // English: Show a confirmation dialog before approving company billing subscription.
  // Arabic: عرض مربع حوار تأكيدي للموافقة على ترقية الفوترة والاشتراك.
  void _showApproveDialog(BuildContext context, int companyId, String companyName) {
    showDialog(
      context: context,
      builder: (dialogContext) {
        return AlertDialog(
          backgroundColor: const Color(0xFF15102A),
          title: const Text('الموافقة على الاشتراك', style: TextStyle(color: Colors.white)),
          content: Text(
            'هل أنت متأكد من تفعيل اشتراك شركة "$companyName"؟ سيتم ترقية حسابهم على الفور.',
            style: const TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(dialogContext),
              child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(dialogContext);
                // English: Dispatch approveBilling command to DashboardCubit.
                // Arabic: استدعاء أمر الموافقة على الاشتراك في الكيوبيت.
                context.read<DashboardCubit>().approveBilling(companyId);
              },
              child: const Text('نعم، وافق', style: TextStyle(color: Colors.green)),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final model = stats;

    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '👑 لوحة تحكم المشرف العام',
            style: TextStyle(
                color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          const Text(
            'مراقبة إحصائيات منصة نبيه بالكامل وإدارة تراخيص الشركات وطلبات الترقية.',
            style: TextStyle(color: Colors.white60, fontSize: 13),
          ),
          const SizedBox(height: 24),
          if (model == null)
            const Center(
              child: Text(
                'فشل تحميل إحصائيات المشرف العام.',
                style: TextStyle(color: Colors.white70),
              ),
            )
          else ...[
            // English: Stats widgets mirroring the web interface dashboard indicators.
            // Arabic: أدوات إحصائية تحاكي مؤشرات لوحة معلومات واجهة الويب.
            Row(
              children: [
                Expanded(
                  child: _buildMetricCard(
                    'الشركات المسجلة',
                    model.totalCompanies.toString(),
                    Icons.business,
                    Colors.purpleAccent,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: _buildMetricCard(
                    'جلسات الواتساب',
                    '${model.connectedSessions}/${model.totalSessions}',
                    Icons.phone_android,
                    Colors.green,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 30),

            // English: Display pending billing approval requests.
            // Arabic: عرض طلبات الموافقة على ترقية الباقات المعلقة.
            const Text(
              'طلبات الترقية المعلقة للموافقة',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            if (model.pendingApprovals.isEmpty)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.02),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.white12),
                ),
                child: const Center(
                  child: Text(
                    'لا توجد طلبات ترقية معلقة حالياً.',
                    style: TextStyle(color: Colors.white60, fontSize: 13),
                  ),
                ),
              )
            else
              ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: model.pendingApprovals.length,
                itemBuilder: (context, index) {
                  final company =
                      model.pendingApprovals[index] as Map<String, dynamic>;
                  return Container(
                    margin: const EdgeInsets.only(bottom: 12),
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: const Color(0xFF1E1446),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                          color: Colors.purpleAccent.withOpacity(0.3)),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              company['name'] as String? ?? 'شركة غير معروفة',
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(height: 6),
                            Text(
                              'الباقة المطلوبة: ${company['plan_name'] ?? 'لا يوجد'}',
                              style: const TextStyle(
                                  color: Colors.purpleAccent, fontSize: 12),
                            ),
                          ],
                        ),
                        ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8)),
                          ),
                          child: const Text('موافقة',
                              style: TextStyle(fontSize: 12)),
                          onPressed: () {
                            _showApproveDialog(
                              context,
                              company['id'] as int? ?? 0,
                              company['name'] as String? ?? 'الشركة',
                            );
                          },
                        ),
                      ],
                    ),
                  );
                },
              ),
            const SizedBox(height: 30),

            // English: Display list of SaaS Companies.
            // Arabic: عرض قائمة الشركات المسجلة وتفاصيل استخداماتها.
            const Text(
              'الشركات والعملاء المشتركين',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: model.companies.length,
              itemBuilder: (context, index) {
                final company = model.companies[index] as Map<String, dynamic>;
                return Container(
                  margin: const EdgeInsets.only(bottom: 16),
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF15102A),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.white.withOpacity(0.05)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            company['name'] as String? ?? 'شركة',
                            style: const TextStyle(
                                color: Colors.white,
                                fontSize: 15,
                                fontWeight: FontWeight.bold),
                          ),
                          _buildSubBadge(
                              company['sub_status'] as String? ?? 'expired',
                              company['plan_name'] as String?),
                        ],
                      ),
                      const Divider(color: Colors.white10, height: 24),
                      _buildDetailRow('الجلسات النشطة',
                          '${company['active_sessions'] ?? 0}/${company['sessions_count'] ?? 0}'),
                      const SizedBox(height: 8),
                      // English: Display SaaS resource usages metrics (Requests, Voice, OCR).
                      // Arabic: عرض مقاييس استخدام موارد النظام (الطلبات، الصوت، تحليل الصور).
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildUsageText('الطلبات',
                              (company['request_usage'] ?? 0).toString()),
                          _buildUsageText('الصوت',
                              (company['voice_usage'] ?? 0).toString()),
                          _buildUsageText(
                              'OCR', (company['ocr_usage'] ?? 0).toString()),
                        ],
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildMetricCard(
      String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF15102A),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.white.withOpacity(0.05)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(height: 12),
          Text(title,
              style: const TextStyle(color: Colors.white60, fontSize: 12)),
          const SizedBox(height: 4),
          Text(value,
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }

  Widget _buildSubBadge(String status, String? planName) {
    final name = planName ?? 'لا توجد باقة';
    Color color = Colors.grey;
    if (status == 'active') {
      color = Colors.green;
    } else if (status == 'trialing') {
      color = Colors.blue;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.15),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color),
      ),
      child: Text(
        name,
        style:
            TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label,
            style: const TextStyle(color: Colors.white60, fontSize: 13)),
        Text(value,
            style: const TextStyle(
                color: Colors.white,
                fontSize: 13,
                fontWeight: FontWeight.bold)),
      ],
    );
  }

  Widget _buildUsageText(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label,
            style: const TextStyle(color: Colors.white54, fontSize: 11)),
        const SizedBox(height: 2),
        Text(value,
            style: const TextStyle(
                color: Colors.purpleAccent,
                fontSize: 13,
                fontWeight: FontWeight.bold)),
      ],
    );
  }
}
