import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/reports_bloc.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../shared/widgets/core_card.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'];

  // Données live du backend
  Map<String, dynamic> _statsMembres = {};
  Map<String, dynamic> _statsCotisations = {};
  Map<String, dynamic> _statsEvenements = {};

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ReportsBloc>().add(const LoadDashboardReports());
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<ReportsBloc, ReportsState>(
      listener: (context, state) {
        if (state is ReportsDashboardLoaded) {
          setState(() {
            _statsMembres = state.statsMembres;
            _statsCotisations = state.statsCotisations;
            _statsEvenements = state.statsEvenements;
          });
        }
        if (state is ReportsError) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(state.message), backgroundColor: AppColors.warning),
          );
        }
        if (state is ReportScheduled) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(state.message), backgroundColor: AppColors.success, behavior: SnackBarBehavior.floating),
          );
        }
        if (state is ReportGenerated) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(state.message), backgroundColor: AppColors.success, behavior: SnackBarBehavior.floating),
          );
        }
      },
      builder: (context, state) {
        return Scaffold(
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          appBar: UFAppBar(
            title: 'Rapports & Analytics',
            moduleGradient: ModuleColors.rapportsGradient,
            actions: [
              IconButton(
                onPressed: () => _showExportDialog(),
                icon: const Icon(Icons.file_download_outlined, size: 20),
                tooltip: 'Exporter',
              ),
            ],
            bottom: TabBar(
              controller: _tabController,
              isScrollable: true,
              labelColor: Colors.white,
              unselectedLabelColor: Colors.white70,
              indicatorColor: Colors.white,
              indicatorSize: TabBarIndicatorSize.label,
              labelStyle: AppTypography.actionText.copyWith(fontSize: 10, fontWeight: FontWeight.bold),
              tabs: const [
                Tab(child: Text('GLOBAL')),
                Tab(child: Text('MEMBRES')),
                Tab(child: Text('ORGS')),
                Tab(child: Text('EVENTS')),
              ],
            ),
          ),
          body: SafeArea(
            top: false,
            child: Column(
              children: [
                if (state is ReportsLoading)
                  const LinearProgressIndicator(
                    minHeight: 2,
                    backgroundColor: Colors.transparent,
                    valueColor: AlwaysStoppedAnimation<Color>(AppColors.primary),
                  ),
                Expanded(
                  child: RefreshIndicator(
                    color: ModuleColors.rapports,
                    onRefresh: () async => context
                        .read<ReportsBloc>()
                        .add(const LoadDashboardReports()),
                    child: TabBarView(
                    controller: _tabController,
                    children: [
                      _buildOverviewTab(),
                      _buildMembersTab(),
                      _buildOrganizationsTab(),
                      _buildEventsTab(),
                    ],
                  ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // _buildHeader(), _buildHeaderStat() et _buildTabBar() supprimés :
  // titre + action Export migrés dans UFAppBar, TabBar dans UFAppBar.bottom.
  // Les KPIs sont toujours disponibles dans _buildKPICards() (onglet Global).

  Widget _buildOverviewTab() {
    return ListView(
      physics: const AlwaysScrollableScrollPhysics(),
      padding: const EdgeInsets.all(12),
      children: [
        _buildKPICards(),
        const SizedBox(height: 12),
        _buildActivityChart(),
        const SizedBox(height: 12),
        _buildQuickReports(),
        const SizedBox(height: 16),
      ],
    );
  }

  Widget _buildKPICards() {
    final totalMembres = _statsMembres['total']?.toString() ?? '--';
    final membresActifs = _statsMembres['membresActifs']?.toString() ?? '--';
    final totalCotisations = _statsCotisations['totalCotisations']?.toString() ?? '--';
    final totalEvenements = _statsEvenements['total']?.toString() ?? '--';

    return Column(
      children: [
        Row(
          children: [
            Expanded(child: _buildKPICard('Total Membres', totalMembres, Icons.people_outline, AppColors.info)),
            const SizedBox(width: 8),
            Expanded(child: _buildKPICard('Membres Actifs', membresActifs, Icons.how_to_reg_outlined, AppColors.success)),
          ],
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(child: _buildKPICard('Cotisations', totalCotisations, Icons.payments_outlined, AppColors.primaryDark)),
            const SizedBox(width: 8),
            Expanded(child: _buildKPICard('Événements', totalEvenements, Icons.event_available_outlined, AppColors.warning)),
          ],
        ),
      ],
    );
  }

  Widget _buildKPICard(String title, String value, IconData icon, Color color) {
    return CoreCard(
      padding: const EdgeInsets.all(10),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(icon, color: color, size: 20),
          ),
          const SizedBox(height: 6),
          Text(
            value,
            style: AppTypography.headerSmall.copyWith(color: color, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),
          Text(
            title.toUpperCase(),
            style: AppTypography.subtitleSmall.copyWith(
              fontSize: 9,
              fontWeight: FontWeight.bold,
              letterSpacing: 0.5,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildActivityChart() {
    return CoreCard(
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.analytics_outlined, color: AppColors.primary, size: 20),
              const SizedBox(width: 8),
              Text(
                'Évolution de l\'Activité'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 10),
          Builder(builder: (context) {
            final isDark = Theme.of(context).brightness == Brightness.dark;
            return Container(
              height: 180,
              decoration: BoxDecoration(
                color: (isDark ? AppColors.borderDark : AppColors.border).withOpacity(0.15),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.auto_graph_outlined,
                        color: isDark ? AppColors.textSecondaryDark : AppColors.textSecondary,
                        size: 40),
                    const SizedBox(height: 12),
                    Text('Visualisation graphique en préparation',
                        style: AppTypography.subtitleSmall),
                  ],
                ),
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildQuickReports() {
    return CoreCard(
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.flash_on_outlined, color: AppColors.warning, size: 20),
              const SizedBox(width: 8),
              Text(
                'Rapports Favoris'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 10),
          _buildQuickReportItem('Bilan Annuel', 'Synthèse financière et activité', Icons.summarize_outlined, () => _generateReport('monthly')),
          _buildQuickReportItem('Engagement Membres', 'Analyse de participation globale', Icons.query_stats_outlined, () => _generateReport('top_members')),
          _buildQuickReportItem('Impact Événements', 'Analyse SEO et participation', Icons.insights_outlined, () => _generateReport('events_analysis')),
        ],
      ),
    );
  }

  Widget _buildQuickReportItem(String title, String subtitle, IconData icon, VoidCallback onTap) {
    return Container(
      margin: const EdgeInsets.only(bottom: 6),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: AppColors.border.withOpacity(0.05),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: AppColors.border.withOpacity(0.1)),
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(icon, color: AppColors.primary, size: 20),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(title, style: AppTypography.actionText),
                    const SizedBox(height: 2),
                    Text(subtitle, style: AppTypography.subtitleSmall.copyWith(fontSize: 10)),
                  ],
                ),
              ),
              Icon(Icons.chevron_right_outlined,
                  color: Theme.of(context).brightness == Brightness.dark
                      ? AppColors.textSecondaryDark
                      : AppColors.textSecondary,
                  size: 20),
            ],
          ),
        ),
      ),
    );
  }

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

  Widget _buildMembersStats() {
    final total = _statsMembres['total']?.toString() ?? '--';
    final nouveaux = _statsMembres['nouveaux30j']?.toString() ?? '--';
    final actifs = _statsMembres['actifs7j']?.toString() ?? '--';

    return CoreCard(
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.people_alt_outlined, color: AppColors.info, size: 20),
              const SizedBox(width: 8),
              Text(
                'Indicateurs Membres'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total', total)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('Nouveaux', nouveaux)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('Actifs %', actifs)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildMembersReports() {
    return CoreCard(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.assignment_ind_outlined, color: AppColors.info, size: 20),
              const SizedBox(width: 12),
              Text(
                'Rapports Membres'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Liste complète des membres', 'Export avec toutes les informations', Icons.list_alt_outlined),
          _buildReportItem('Analyse d\'engagement', 'Participation et activité des membres', Icons.trending_up_outlined),
          _buildReportItem('Segmentation démographique', 'Répartition par âge, région, etc.', Icons.pie_chart_outline),
        ],
      ),
    );
  }

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

  Widget _buildOrganizationsStats() {
    final total = _statsMembres['totalOrganisations']?.toString() ?? '--';
    final actives = _statsMembres['organisationsActives']?.toString() ?? '--';
    final moy = _statsMembres['membresParOrganisation']?.toString() ?? '--';

    return CoreCard(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.business_center_outlined, color: AppColors.primary, size: 20),
              const SizedBox(width: 12),
              Text(
                'Indicateurs Organisations'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total', total)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('Actives', actives)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('Membres moy.', moy)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildOrganizationsReports() {
    return CoreCard(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.folder_shared_outlined, color: AppColors.primary, size: 20),
              const SizedBox(width: 12),
              Text(
                'Rapports Structures'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Annuaire des organisations', 'Liste complète avec contacts', Icons.contact_phone_outlined),
          _buildReportItem('Performance par organisation', 'Activité et engagement', Icons.bar_chart_outlined),
          _buildReportItem('Analyse de croissance', 'Évolution du nombre de membres', Icons.trending_up_outlined),
        ],
      ),
    );
  }

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

  Widget _buildEventsStats() {
    final total = _statsEvenements['total']?.toString() ?? '--';
    final venir = _statsEvenements['aVenir']?.toString() ?? '--';
    final participation = _statsEvenements['participationMoyenne']?.toString() ?? '--';

    return CoreCard(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.event_note_outlined, color: AppColors.warning, size: 20),
              const SizedBox(width: 12),
              Text(
                'Indicateurs Événements'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(child: _buildStatItem('Total', total)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('À Venir', venir)),
              Container(width: 1, height: 30, color: AppColors.border.withOpacity(0.2)),
              Expanded(child: _buildStatItem('Part. moyenne', participation)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildEventsReports() {
    return CoreCard(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.history_edu_outlined, color: AppColors.warning, size: 20),
              const SizedBox(width: 12),
              Text(
                'Rapports Logistique'.toUpperCase(),
                style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
              ),
            ],
          ),
          const SizedBox(height: 16),
          _buildReportItem('Calendrier des événements', 'Planning complet avec détails', Icons.calendar_today_outlined),
          _buildReportItem('Analyse de participation', 'Taux de participation et feedback', Icons.people_outline),
          _buildReportItem('ROI des événements', 'Retour sur investissement financier', Icons.analytics_outlined),
        ],
      ),
    );
  }

  // Composants communs
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: AppTypography.headerSmall.copyWith(color: AppColors.primary, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 4),
        Text(
          label.toUpperCase(),
          style: AppTypography.subtitleSmall.copyWith(fontSize: 8, fontWeight: FontWeight.bold),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildReportItem(String title, String subtitle, IconData icon) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: InkWell(
        onTap: () => _generateReport(title.toLowerCase().replaceAll(' ', '_')),
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: AppColors.border.withOpacity(0.05),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: AppColors.border.withOpacity(0.1)),
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(icon, color: AppColors.primary, size: 20),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(title, style: AppTypography.actionText),
                    const SizedBox(height: 2),
                    Text(subtitle, style: AppTypography.subtitleSmall.copyWith(fontSize: 10)),
                  ],
                ),
              ),
              Icon(Icons.file_download_outlined,
                  color: Theme.of(context).brightness == Brightness.dark
                      ? AppColors.textSecondaryDark
                      : AppColors.textSecondary,
                  size: 20),
            ],
          ),
        ),
      ),
    );
  }

  // 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();
              context.read<ReportsBloc>().add(GenerateReportRequested('export', format: _selectedFormat));
            },
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.primary, foregroundColor: AppColors.onPrimary),
            child: const Text('Exporter'),
          ),
        ],
      ),
    );
  }

  void _scheduleReport() {
    context.read<ReportsBloc>().add(const ScheduleReportRequested());
  }

  void _generateReport(String type) {
    context.read<ReportsBloc>().add(GenerateReportRequested(type));
  }

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: AppColors.success, behavior: SnackBarBehavior.floating),
    );
  }
}
