import 'package:flutter/material.dart';

/// Dashboard pour le Super Administrateur
/// Interface mobile optimisée avec drawer de navigation
class SuperAdminDashboard extends StatefulWidget {
  const SuperAdminDashboard({super.key});

  @override
  State<SuperAdminDashboard> createState() => _SuperAdminDashboardState();
}

class _SuperAdminDashboardState extends State<SuperAdminDashboard> {
  int _selectedIndex = 0;

  final List<String> _sectionTitles = [
    'Vue Globale',
    'Organisations',
    'Utilisateurs',
    'Système',
    'Analytics',
    'Sécurité',
    'Configuration',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        title: Text(
          'Command Center - ${_sectionTitles[_selectedIndex]}',
          style: const TextStyle(
            color: Color(0xFF6C5CE7),
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 2,
        centerTitle: false,
      ),
      drawer: _buildDrawer(context),
      body: _buildSelectedContent(),
    );
  }

  /// Drawer de navigation mobile
  Widget _buildDrawer(BuildContext context) {
    return Drawer(
      child: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF6C5CE7),
              Color(0xFF5A4FCF),
              Color(0xFF4834D4),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // Profil utilisateur
              _buildUserProfile(),
              const SizedBox(height: 16),

              // Menu de navigation
              Expanded(
                child: _buildNavigationMenu(),
              ),

              // Actions du bas
              _buildBottomActions(),
            ],
          ),
        ),
      ),
    );
  }

  /// Profil utilisateur dans la sidebar
  Widget _buildUserProfile() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // Photo de profil
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(30),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: const Icon(
              Icons.admin_panel_settings,
              color: Colors.white,
              size: 30,
            ),
          ),

          const SizedBox(height: 8),

          // Nom et email
          const Text(
            'Super Admin',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          const Text(
            'superadmin@unionflow.com',
            style: TextStyle(
              color: Colors.white70,
              fontSize: 11,
            ),
          ),

          const SizedBox(height: 8),

          // Badge de rôle
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 8,
              vertical: 4,
            ),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
              ),
            ),
            child: const Text(
              'SUPER_ADMINISTRATEUR',
              style: TextStyle(
                color: Colors.white,
                fontSize: 9,
                fontWeight: FontWeight.w600,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Menu de navigation dans la sidebar
  Widget _buildNavigationMenu() {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      itemCount: _sectionTitles.length,
      itemBuilder: (context, index) {
        final isSelected = _selectedIndex == index;
        return Container(
          margin: const EdgeInsets.only(bottom: 4),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () {
                Navigator.of(context).pop(); // Fermer le drawer
                setState(() {
                  _selectedIndex = index;
                });
              },
              borderRadius: BorderRadius.circular(8),
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 8,
                ),
                decoration: BoxDecoration(
                  color: isSelected
                    ? Colors.white.withOpacity(0.2)
                    : Colors.transparent,
                  borderRadius: BorderRadius.circular(8),
                  border: isSelected
                    ? Border.all(color: Colors.white.withOpacity(0.3))
                    : null,
                ),
                child: Row(
                  children: [
                    Icon(
                      _getSectionIcon(index),
                      color: Colors.white,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        _sectionTitles[index],
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: isSelected
                            ? FontWeight.w600
                            : FontWeight.normal,
                        ),
                      ),
                    ),
                    if (isSelected)
                      const Icon(
                        Icons.chevron_right,
                        color: Colors.white,
                        size: 16,
                      ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// Actions du bas
  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton.icon(
          onPressed: () {
            Navigator.of(context).pop();
            // TODO: Implémenter la déconnexion
          },
          icon: const Icon(Icons.logout, size: 16),
          label: const Text('Déconnexion'),
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.white.withOpacity(0.2),
            foregroundColor: Colors.white,
            elevation: 0,
            padding: const EdgeInsets.symmetric(vertical: 8),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
              side: BorderSide(
                color: Colors.white.withOpacity(0.3),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// Contenu de la section sélectionnée
  Widget _buildSelectedContent() {
    switch (_selectedIndex) {
      case 0:
        return _buildGlobalOverviewContent();
      case 1:
        return _buildOrganizationsContent();
      case 2:
        return _buildUsersContent();
      case 3:
        return _buildSystemContent();
      case 4:
        return _buildAnalyticsContent();
      case 5:
        return _buildSecurityContent();
      case 6:
        return _buildConfigurationContent();
      default:
        return _buildGlobalOverviewContent();
    }
  }

  /// Icône pour chaque section
  IconData _getSectionIcon(int index) {
    switch (index) {
      case 0: return Icons.dashboard;
      case 1: return Icons.business;
      case 2: return Icons.people;
      case 3: return Icons.computer;
      case 4: return Icons.analytics;
      case 5: return Icons.security;
      case 6: return Icons.settings;
      default: return Icons.dashboard;
    }
  }

  /// Vue Globale - Métriques système simplifiées
  Widget _buildGlobalOverviewContent() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // KPIs système en temps réel
          _buildSimpleKPIsSection(),
          const SizedBox(height: 16),

          // Performance serveur
          _buildSimpleServerSection(),
          const SizedBox(height: 16),

          // Alertes importantes
          _buildSimpleAlertsSection(),
          const SizedBox(height: 16),

          // Activité récente
          _buildSimpleActivitySection(),
        ],
      ),
    );
  }

  /// Section KPIs simplifiée
  Widget _buildSimpleKPIsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Métriques Système',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Color(0xFF6C5CE7),
            fontSize: 20,
          ),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildSimpleKPICard(
                'Organisations',
                '247',
                '+12 ce mois',
                Icons.business,
                const Color(0xFF0984E3),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildSimpleKPICard(
                'Utilisateurs',
                '15,847',
                '+1,234 ce mois',
                Icons.people,
                const Color(0xFF00B894),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: _buildSimpleKPICard(
                'Uptime',
                '99.97%',
                '30 derniers jours',
                Icons.trending_up,
                const Color(0xFF00CEC9),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildSimpleKPICard(
                'Temps Réponse',
                '1.2s',
                'Moyenne 24h',
                Icons.speed,
                const Color(0xFFE17055),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// Carte KPI simplifiée
  Widget _buildSimpleKPICard(
    String title,
    String value,
    String subtitle,
    IconData icon,
    Color color,
  ) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: color, size: 20),
              const Spacer(),
              Text(
                value,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: color,
                  fontSize: 18,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            title,
            style: const TextStyle(
              fontWeight: FontWeight.w600,
              color: Colors.black87,
              fontSize: 12,
            ),
          ),
          Text(
            subtitle,
            style: const TextStyle(
              color: Colors.grey,
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }

  /// Section serveur simplifiée
  Widget _buildSimpleServerSection() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Performance Serveur',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 12),
          _buildMetricRow('CPU', '67.3%', Colors.orange),
          const SizedBox(height: 8),
          _buildMetricRow('RAM', '12.4 GB / 16 GB', Colors.blue),
          const SizedBox(height: 8),
          _buildMetricRow('Disque', '847 GB / 1 TB', Colors.red),
        ],
      ),
    );
  }

  /// Ligne de métrique
  Widget _buildMetricRow(String label, String value, Color color) {
    return Row(
      children: [
        Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 8),
        Text(
          label,
          style: const TextStyle(fontWeight: FontWeight.w600),
        ),
        const Spacer(),
        Text(
          value,
          style: TextStyle(
            color: color,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  /// Section alertes simplifiée
  Widget _buildSimpleAlertsSection() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Alertes Système',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 12),
          _buildAlertRow('Charge CPU élevée', 'Serveur principal', Colors.orange),
          const SizedBox(height: 8),
          _buildAlertRow('Espace disque faible', 'Base de données', Colors.red),
          const SizedBox(height: 8),
          _buildAlertRow('Connexions élevées', 'Load balancer', Colors.amber),
        ],
      ),
    );
  }

  /// Ligne d'alerte
  Widget _buildAlertRow(String title, String source, Color color) {
    return Row(
      children: [
        Icon(Icons.warning, color: color, size: 16),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 12,
                ),
              ),
              Text(
                source,
                style: const TextStyle(
                  color: Colors.grey,
                  fontSize: 10,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Section activité simplifiée
  Widget _buildSimpleActivitySection() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Activité Récente',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 12),
          _buildActivityRow('Nouvelle organisation créée', 'il y a 2h'),
          const SizedBox(height: 8),
          _buildActivityRow('Utilisateur connecté', 'il y a 5min'),
          const SizedBox(height: 8),
          _buildActivityRow('Sauvegarde terminée', 'il y a 1h'),
        ],
      ),
    );
  }

  /// Ligne d'activité
  Widget _buildActivityRow(String title, String time) {
    return Row(
      children: [
        Container(
          width: 8,
          height: 8,
          decoration: const BoxDecoration(
            color: Color(0xFF6C5CE7),
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            title,
            style: const TextStyle(fontSize: 12),
          ),
        ),
        Text(
          time,
          style: const TextStyle(
            color: Colors.grey,
            fontSize: 10,
          ),
        ),
      ],
    );
  }

  /// Organisations Content
  Widget _buildOrganizationsContent() {
    return const Center(
      child: Text(
        'Gestion des Organisations\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// Users Content
  Widget _buildUsersContent() {
    return const Center(
      child: Text(
        'Gestion des Utilisateurs\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// System Content
  Widget _buildSystemContent() {
    return const Center(
      child: Text(
        'Monitoring Système\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// Analytics Content
  Widget _buildAnalyticsContent() {
    return const Center(
      child: Text(
        'Analytics Avancées\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// Security Content
  Widget _buildSecurityContent() {
    return const Center(
      child: Text(
        'Sécurité et Audit\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// Configuration Content
  Widget _buildConfigurationContent() {
    return const Center(
      child: Text(
        'Configuration Système\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }
}
