import 'package:flutter/material.dart';

/// Page Rapports & Analytics - UnionFlow Mobile
/// 
/// Page complète de génération et consultation des rapports avec
/// analytics avancés, graphiques et export de données.
class ReportsPage extends StatefulWidget {
  const ReportsPage({super.key});

  @override
  State<ReportsPage> createState() => _ReportsPageState();
}

class _ReportsPageState extends State<ReportsPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  
  String _selectedPeriod = 'Dernier mois';
  String _selectedFormat = 'PDF';
  
  final List<String> _periods = ['Dernière semaine', 'Dernier mois', 'Dernier trimestre', 'Dernière année'];
  final List<String> _formats = ['PDF', 'Excel', 'CSV', 'JSON'];

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      body: Column(
        children: [
          _buildHeader(),
          _buildTabBar(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildOverviewTab(),
                _buildMembersTab(),
                _buildOrganizationsTab(),
                _buildEventsTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Header harmonisé
  Widget _buildHeader() {
    return Container(
      margin: const EdgeInsets.all(12),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF6C5CE7), Color(0xFF5A4FCF)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF6C5CE7).withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Icon(Icons.assessment, color: Colors.white, size: 24),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Rapports & Analytics',
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
                    ),
                    Text(
                      'Statistiques et analyses détaillées',
                      style: TextStyle(fontSize: 14, color: Colors.white.withOpacity(0.8)),
                    ),
                  ],
                ),
              ),
              Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: IconButton(
                      onPressed: () => _showExportDialog(),
                      icon: const Icon(Icons.download, color: Colors.white),
                      tooltip: 'Exporter rapport',
                    ),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: IconButton(
                      onPressed: () => _scheduleReport(),
                      icon: const Icon(Icons.schedule, color: Colors.white),
                      tooltip: 'Programmer rapport',
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(child: _buildStatCard('Membres', '1,247', Icons.people, Colors.blue)),
              const SizedBox(width: 12),
              Expanded(child: _buildStatCard('Organisations', '89', Icons.business, Colors.green)),
              const SizedBox(width: 12),
              Expanded(child: _buildStatCard('Événements', '156', Icons.event, Colors.orange)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.15),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Icon(icon, color: Colors.white, size: 20),
          const SizedBox(height: 4),
          Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.white)),
          Text(label, style: TextStyle(fontSize: 10, color: Colors.white.withOpacity(0.8))),
        ],
      ),
    );
  }

  /// Barre d'onglets
  Widget _buildTabBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: TabBar(
        controller: _tabController,
        labelColor: const Color(0xFF6C5CE7),
        unselectedLabelColor: Colors.grey[600],
        indicatorColor: const Color(0xFF6C5CE7),
        labelStyle: const TextStyle(fontWeight: FontWeight.w600, fontSize: 11),
        tabs: const [
          Tab(icon: Icon(Icons.dashboard, size: 16), text: 'Vue d\'ensemble'),
          Tab(icon: Icon(Icons.people, size: 16), text: 'Membres'),
          Tab(icon: Icon(Icons.business, size: 16), text: 'Organisations'),
          Tab(icon: Icon(Icons.event, size: 16), text: 'Événements'),
        ],
      ),
    );
  }

  /// Onglet vue d'ensemble
  Widget _buildOverviewTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          const SizedBox(height: 16),
          _buildKPICards(),
          const SizedBox(height: 16),
          _buildActivityChart(),
          const SizedBox(height: 16),
          _buildQuickReports(),
          const SizedBox(height: 80),
        ],
      ),
    );
  }

  /// Cartes KPI
  Widget _buildKPICards() {
    return Column(
      children: [
        Row(
          children: [
            Expanded(child: _buildKPICard('Croissance membres', '+12.5%', Icons.trending_up, Colors.green)),
            const SizedBox(width: 12),
            Expanded(child: _buildKPICard('Taux d\'engagement', '78%', Icons.favorite, Colors.red)),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(child: _buildKPICard('Événements actifs', '23', Icons.event_available, Colors.blue)),
            const SizedBox(width: 12),
            Expanded(child: _buildKPICard('Satisfaction', '4.8/5', Icons.star, Colors.amber)),
          ],
        ),
      ],
    );
  }

  Widget _buildKPICard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 32),
          const SizedBox(height: 8),
          Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: color)),
          Text(title, style: TextStyle(fontSize: 12, color: Colors.grey[600]), textAlign: TextAlign.center),
        ],
      ),
    );
  }

  /// Graphique d'activité
  Widget _buildActivityChart() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.show_chart, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Activité des 30 derniers jours', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          Container(
            height: 120,
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Center(
              child: Text('Graphique d\'activité\n(Intégration Chart.js à venir)', textAlign: TextAlign.center, style: TextStyle(color: Colors.grey)),
            ),
          ),
        ],
      ),
    );
  }

  /// Rapports rapides
  Widget _buildQuickReports() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.flash_on, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Rapports rapides', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          _buildQuickReportItem('Rapport mensuel', 'Synthèse complète du mois', Icons.calendar_month, () => _generateReport('monthly')),
          _buildQuickReportItem('Top membres actifs', 'Classement des membres les plus actifs', Icons.leaderboard, () => _generateReport('top_members')),
          _buildQuickReportItem('Analyse des événements', 'Performance et participation aux événements', Icons.analytics, () => _generateReport('events_analysis')),
        ],
      ),
    );
  }

  Widget _buildQuickReportItem(String title, String subtitle, IconData icon, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Icon(icon, color: const Color(0xFF6C5CE7), size: 20),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF1F2937))),
                  Text(subtitle, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
                ],
              ),
            ),
            Icon(Icons.arrow_forward_ios, color: Colors.grey[400], size: 16),
          ],
        ),
      ),
    );
  }

  /// Onglet membres
  Widget _buildMembersTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          const SizedBox(height: 16),
          _buildMembersStats(),
          const SizedBox(height: 16),
          _buildMembersReports(),
          const SizedBox(height: 80),
        ],
      ),
    );
  }

  Widget _buildMembersStats() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.people, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Statistiques membres', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total membres', '1,247')),
              Expanded(child: _buildStatItem('Nouveaux (30j)', '+156')),
              Expanded(child: _buildStatItem('Actifs (7j)', '892')),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildMembersReports() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.description, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Rapports membres', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Liste complète des membres', 'Export avec toutes les informations', Icons.list_alt),
          _buildReportItem('Analyse d\'engagement', 'Participation et activité des membres', Icons.trending_up),
          _buildReportItem('Segmentation démographique', 'Répartition par âge, région, etc.', Icons.pie_chart),
        ],
      ),
    );
  }

  /// Onglet organisations
  Widget _buildOrganizationsTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          const SizedBox(height: 16),
          _buildOrganizationsStats(),
          const SizedBox(height: 16),
          _buildOrganizationsReports(),
          const SizedBox(height: 80),
        ],
      ),
    );
  }

  Widget _buildOrganizationsStats() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.business, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Statistiques organisations', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total orgs', '89')),
              Expanded(child: _buildStatItem('Actives', '67')),
              Expanded(child: _buildStatItem('Membres moy.', '14')),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildOrganizationsReports() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.description, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Rapports organisations', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Annuaire des organisations', 'Liste complète avec contacts', Icons.contact_phone),
          _buildReportItem('Performance par organisation', 'Activité et engagement', Icons.bar_chart),
          _buildReportItem('Analyse de croissance', 'Évolution du nombre de membres', Icons.show_chart),
        ],
      ),
    );
  }

  /// Onglet événements
  Widget _buildEventsTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          const SizedBox(height: 16),
          _buildEventsStats(),
          const SizedBox(height: 16),
          _buildEventsReports(),
          const SizedBox(height: 80),
        ],
      ),
    );
  }

  Widget _buildEventsStats() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.event, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Statistiques événements', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total événements', '156')),
              Expanded(child: _buildStatItem('À venir', '23')),
              Expanded(child: _buildStatItem('Participation moy.', '45')),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildEventsReports() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, 2))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.description, color: Color(0xFF6C5CE7), size: 20),
              const SizedBox(width: 8),
              Text('Rapports événements', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.grey[800])),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Calendrier des événements', 'Planning complet avec détails', Icons.calendar_today),
          _buildReportItem('Analyse de participation', 'Taux de participation et feedback', Icons.people_outline),
          _buildReportItem('ROI des événements', 'Retour sur investissement', Icons.attach_money),
        ],
      ),
    );
  }

  // Composants communs
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(value, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF6C5CE7))),
        Text(label, style: TextStyle(fontSize: 12, color: Colors.grey[600]), textAlign: TextAlign.center),
      ],
    );
  }

  Widget _buildReportItem(String title, String subtitle, IconData icon) {
    return InkWell(
      onTap: () => _generateReport(title.toLowerCase().replaceAll(' ', '_')),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Icon(icon, color: const Color(0xFF6C5CE7), size: 20),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF1F2937))),
                  Text(subtitle, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
                ],
              ),
            ),
            Icon(Icons.download, color: Colors.grey[400], size: 16),
          ],
        ),
      ),
    );
  }

  // Méthodes d'action
  void _showExportDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Exporter rapport'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            DropdownButtonFormField<String>(
              value: _selectedPeriod,
              decoration: const InputDecoration(labelText: 'Période'),
              items: _periods.map((period) => DropdownMenuItem(value: period, child: Text(period))).toList(),
              onChanged: (value) => setState(() => _selectedPeriod = value!),
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(
              value: _selectedFormat,
              decoration: const InputDecoration(labelText: 'Format'),
              items: _formats.map((format) => DropdownMenuItem(value: format, child: Text(format))).toList(),
              onChanged: (value) => setState(() => _selectedFormat = value!),
            ),
          ],
        ),
        actions: [
          TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Annuler')),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _showSuccessSnackBar('Export lancé - Vous recevrez un email');
            },
            style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF6C5CE7), foregroundColor: Colors.white),
            child: const Text('Exporter'),
          ),
        ],
      ),
    );
  }

  void _scheduleReport() => _showSuccessSnackBar('Programmation de rapport configurée');
  void _generateReport(String type) => _showSuccessSnackBar('Génération du rapport "$type" lancée');

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: const Color(0xFF00B894), behavior: SnackBarBehavior.floating),
    );
  }
}
