/// Dashboard Gestionnaire RH - Interface Ressources Humaines
/// Outils spécialisés pour la gestion des employés et RH
library hr_manager_dashboard;

import 'package:flutter/material.dart';

/// Dashboard spécialisé pour Gestionnaire RH
/// 
/// Fonctionnalités RH :
/// - Gestion des employés
/// - Recrutement et onboarding
/// - Évaluations de performance
/// - Congés et absences
/// - Reporting RH
/// - Formation et développement
class HRManagerDashboard extends StatefulWidget {
  const HRManagerDashboard({super.key});

  @override
  State<HRManagerDashboard> createState() => _HRManagerDashboardState();
}

class _HRManagerDashboardState extends State<HRManagerDashboard>
    with TickerProviderStateMixin {
  late TabController _tabController;
  int _selectedIndex = 0;

  final List<String> _hrSections = [
    'Vue d\'ensemble',
    'Employés',
    'Recrutement',
    'Évaluations',
    'Congés',
    'Formation',
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _hrSections.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        title: Text(
          'RH Manager - ${_hrSections[_selectedIndex]}',
          style: const TextStyle(
            color: Color(0xFF00B894),
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 2,
        centerTitle: false,
        actions: [
          // Recherche employés
          IconButton(
            icon: const Icon(Icons.search, color: Color(0xFF00B894)),
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Recherche avancée - Fonctionnalité à implémenter'),
                  backgroundColor: Color(0xFF00B894),
                ),
              );
            },
            tooltip: 'Rechercher employés',
          ),
          // Notifications RH
          IconButton(
            icon: const Icon(Icons.notifications_outlined, color: Color(0xFF00B894)),
            onPressed: () => _showHRNotifications(),
            tooltip: 'Notifications RH',
          ),
          // Menu RH
          PopupMenuButton<String>(
            icon: const Icon(Icons.more_vert, color: Color(0xFF00B894)),
            onSelected: (value) {
              switch (value) {
                case 'reports':
                  _generateHRReports();
                  break;
                case 'settings':
                  _openHRSettings();
                  break;
                case 'export':
                  _exportHRData();
                  break;
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'reports',
                child: Row(
                  children: [
                    Icon(Icons.assessment, size: 20, color: Color(0xFF00B894)),
                    SizedBox(width: 12),
                    Text('Rapports RH'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'settings',
                child: Row(
                  children: [
                    Icon(Icons.settings, size: 20, color: Color(0xFF00B894)),
                    SizedBox(width: 12),
                    Text('Paramètres RH'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'export',
                child: Row(
                  children: [
                    Icon(Icons.download, size: 20, color: Color(0xFF00B894)),
                    SizedBox(width: 12),
                    Text('Exporter données'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      drawer: _buildHRDrawer(),
      body: Stack(
        children: [
          _buildSelectedContent(),
          // Navigation rapide RH
          Positioned(
            bottom: 20,
            left: 20,
            right: 20,
            child: _buildHRQuickNavigation(),
          ),
        ],
      ),
    );
  }

  /// Drawer de navigation RH
  Widget _buildHRDrawer() {
    return Drawer(
      child: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF00B894),
              Color(0xFF00A085),
              Color(0xFF008B75),
            ],
          ),
        ),
        child: Column(
          children: [
            // Header RH
            Container(
              padding: const EdgeInsets.fromLTRB(20, 60, 20, 20),
              child: Row(
                children: [
                  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.people,
                      color: Colors.white,
                      size: 30,
                    ),
                  ),
                  const SizedBox(width: 16),
                  const Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Gestionnaire RH',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          'Ressources Humaines',
                          style: TextStyle(
                            color: Colors.white70,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            
            // Menu de navigation
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                itemCount: _hrSections.length,
                itemBuilder: (context, index) {
                  final isSelected = _selectedIndex == index;
                  return Container(
                    margin: const EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      color: isSelected 
                          ? Colors.white.withOpacity(0.2)
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: ListTile(
                      leading: Icon(
                        _getHRSectionIcon(index),
                        color: Colors.white,
                        size: 22,
                      ),
                      title: Text(
                        _hrSections[index],
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                        ),
                      ),
                      onTap: () {
                        setState(() => _selectedIndex = index);
                        Navigator.pop(context);
                      },
                    ),
                  );
                },
              ),
            ),
            
            // Footer avec déconnexion
            Container(
              padding: const EdgeInsets.all(16),
              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,
                  minimumSize: const Size(double.infinity, 40),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Icône pour chaque section RH
  IconData _getHRSectionIcon(int index) {
    switch (index) {
      case 0: return Icons.dashboard;
      case 1: return Icons.people;
      case 2: return Icons.person_add;
      case 3: return Icons.star_rate;
      case 4: return Icons.event_busy;
      case 5: return Icons.school;
      default: return Icons.dashboard;
    }
  }

  /// Contenu de la section sélectionnée
  Widget _buildSelectedContent() {
    switch (_selectedIndex) {
      case 0:
        return _buildOverviewContent();
      case 1:
        return _buildEmployeesContent();
      case 2:
        return _buildRecruitmentContent();
      case 3:
        return _buildEvaluationsContent();
      case 4:
        return _buildLeavesContent();
      case 5:
        return _buildTrainingContent();
      default:
        return _buildOverviewContent();
    }
  }

  /// Vue d'ensemble RH
  Widget _buildOverviewContent() {
    return SingleChildScrollView(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 80),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header avec statut RH
          _buildHRStatusHeader(),
          const SizedBox(height: 20),
          
          // KPIs RH
          _buildHRKPIsSection(),
          const SizedBox(height: 20),
          
          // Actions rapides RH
          _buildHRQuickActions(),
          const SizedBox(height: 20),
          
          // Alertes RH importantes
          _buildHRAlerts(),
        ],
      ),
    );
  }

  /// Placeholder pour les autres sections
  Widget _buildEmployeesContent() {
    return const Center(
      child: Text(
        'Gestion des Employés\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  Widget _buildRecruitmentContent() {
    return const Center(
      child: Text(
        'Recrutement\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  Widget _buildEvaluationsContent() {
    return const Center(
      child: Text(
        'Évaluations\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  Widget _buildLeavesContent() {
    return const Center(
      child: Text(
        'Congés et Absences\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  Widget _buildTrainingContent() {
    return const Center(
      child: Text(
        'Formation\n(En développement)',
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 18),
      ),
    );
  }

  /// Header avec statut RH
  Widget _buildHRStatusHeader() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF00B894), Color(0xFF00A085)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF00B894).withOpacity(0.3),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Département RH Actif',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Dernière sync: ${DateTime.now().hour.toString().padLeft(2, '0')}:${DateTime.now().minute.toString().padLeft(2, '0')}',
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.8),
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Icon(
              Icons.people,
              color: Colors.white,
              size: 28,
            ),
          ),
        ],
      ),
    );
  }

  /// Section KPIs RH
  Widget _buildHRKPIsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Indicateurs RH',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildHRKPICard(
                'Employés Actifs',
                '247',
                '+12 ce mois',
                Icons.people,
                const Color(0xFF00B894),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildHRKPICard(
                'Candidatures',
                '34',
                '+8 cette semaine',
                Icons.person_add,
                const Color(0xFF0984E3),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildHRKPICard(
                'En Congé',
                '18',
                '7.3% de l\'effectif',
                Icons.event_busy,
                const Color(0xFFFDAB00),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildHRKPICard(
                'Évaluations',
                '156',
                '89% complétées',
                Icons.star_rate,
                const Color(0xFFE17055),
              ),
            ),
          ],
        ),
      ],
    );
  }

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

  /// Actions rapides RH
  Widget _buildHRQuickActions() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Actions Rapides',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
          childAspectRatio: 1.5,
          children: [
            _buildHRActionCard(
              'Nouveau Employé',
              Icons.person_add,
              const Color(0xFF00B894),
              () => _addNewEmployee(),
            ),
            _buildHRActionCard(
              'Demandes Congés',
              Icons.event_busy,
              const Color(0xFFFDAB00),
              () => _viewLeaveRequests(),
            ),
            _buildHRActionCard(
              'Évaluations',
              Icons.star_rate,
              const Color(0xFFE17055),
              () => _viewEvaluations(),
            ),
            _buildHRActionCard(
              'Recrutement',
              Icons.work,
              const Color(0xFF0984E3),
              () => _viewRecruitment(),
            ),
          ],
        ),
      ],
    );
  }

  /// Widget pour une action RH
  Widget _buildHRActionCard(
    String title,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: color.withOpacity(0.2)),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                color: color,
                size: 24,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: const TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 12,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  /// Alertes RH importantes
  Widget _buildHRAlerts() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Alertes Importantes',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        _buildHRAlertItem(
          'Évaluations en retard',
          '12 évaluations annuelles à finaliser',
          Icons.warning,
          const Color(0xFFE17055),
        ),
        const SizedBox(height: 8),
        _buildHRAlertItem(
          'Congés à approuver',
          '5 demandes de congé en attente',
          Icons.pending_actions,
          const Color(0xFFFDAB00),
        ),
        const SizedBox(height: 8),
        _buildHRAlertItem(
          'Nouveaux candidats',
          '8 candidatures reçues cette semaine',
          Icons.person_add,
          const Color(0xFF0984E3),
        ),
      ],
    );
  }

  /// Widget pour un élément d'alerte RH
  Widget _buildHRAlertItem(
    String title,
    String message,
    IconData icon,
    Color color,
  ) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(icon, color: color, size: 20),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 12,
                    color: color,
                  ),
                ),
                Text(
                  message,
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Navigation rapide RH
  Widget _buildHRQuickNavigation() {
    return Container(
      height: 60,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(30),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildHRNavItem(Icons.dashboard, 'Vue', 0),
          _buildHRNavItem(Icons.people, 'Employés', 1),
          _buildHRNavItem(Icons.person_add, 'Recrutement', 2),
          _buildHRNavItem(Icons.star_rate, 'Évaluations', 3),
          _buildHRNavItem(Icons.event_busy, 'Congés', 4),
        ],
      ),
    );
  }

  /// Widget pour un élément de navigation RH
  Widget _buildHRNavItem(IconData icon, String label, int index) {
    final isSelected = _selectedIndex == index;
    return GestureDetector(
      onTap: () => setState(() => _selectedIndex = index),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: isSelected
                    ? const Color(0xFF00B894).withOpacity(0.1)
                    : Colors.transparent,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                size: 18,
                color: isSelected
                    ? const Color(0xFF00B894)
                    : Colors.grey[600],
              ),
            ),
            const SizedBox(height: 2),
            Text(
              label,
              style: TextStyle(
                fontSize: 9,
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                color: isSelected
                    ? const Color(0xFF00B894)
                    : Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Méthodes d'action
  void _showHRNotifications() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Notifications RH - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  void _generateHRReports() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Rapports RH - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  void _openHRSettings() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Paramètres RH - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  void _exportHRData() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Export données RH - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  void _addNewEmployee() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Ajouter employé - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  void _viewLeaveRequests() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Demandes de congé - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFFFDAB00),
      ),
    );
  }

  void _viewEvaluations() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Évaluations - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFFE17055),
      ),
    );
  }

  void _viewRecruitment() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Recrutement - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF0984E3),
      ),
    );
  }
}
