import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'dart:async';
import '../../../domain/entities/dashboard_entity.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../../../../shared/design_system/dashboard_theme.dart';

/// Widget de métriques en temps réel avec animations
class RealTimeMetricsWidget extends StatefulWidget {
  final String organizationId;
  final String userId;
  final Duration refreshInterval;

  const RealTimeMetricsWidget({
    super.key,
    required this.organizationId,
    required this.userId,
    this.refreshInterval = const Duration(minutes: 5),
  });

  @override
  State<RealTimeMetricsWidget> createState() => _RealTimeMetricsWidgetState();
}

class _RealTimeMetricsWidgetState extends State<RealTimeMetricsWidget>
    with TickerProviderStateMixin {
  Timer? _refreshTimer;
  late AnimationController _pulseController;
  late AnimationController _countController;
  late Animation<double> _pulseAnimation;
  late Animation<double> _countAnimation;

  @override
  void initState() {
    super.initState();
    _setupAnimations();
    _startAutoRefresh();
  }

  void _setupAnimations() {
    _pulseController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    
    _countController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _pulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _pulseController,
      curve: Curves.easeInOut,
    ));

    _countAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _countController,
      curve: Curves.easeOutCubic,
    ));

    _pulseController.repeat(reverse: true);
  }

  void _startAutoRefresh() {
    _refreshTimer = Timer.periodic(widget.refreshInterval, (timer) {
      if (mounted) {
        context.read<DashboardBloc>().add(RefreshDashboardData(
          organizationId: widget.organizationId,
          userId: widget.userId,
        ));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: DashboardTheme.gradientCardDecoration,
      padding: const EdgeInsets.all(DashboardTheme.spacing20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          const SizedBox(height: DashboardTheme.spacing20),
          BlocConsumer<DashboardBloc, DashboardState>(
            listener: (context, state) {
              if (state is DashboardLoaded) {
                _countController.forward(from: 0);
              }
            },
            builder: (context, state) {
              if (state is DashboardLoading) {
                return _buildLoadingMetrics();
              } else if (state is DashboardLoaded || state is DashboardRefreshing) {
                final data = state is DashboardLoaded 
                    ? state.dashboardData 
                    : (state as DashboardRefreshing).dashboardData;
                return _buildMetrics(data);
              } else if (state is DashboardError) {
                return _buildErrorMetrics();
              }
              return _buildEmptyMetrics();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Row(
      children: [
        AnimatedBuilder(
          animation: _pulseAnimation,
          builder: (context, child) {
            return Transform.scale(
              scale: _pulseAnimation.value,
              child: Container(
                padding: const EdgeInsets.all(DashboardTheme.spacing8),
                decoration: BoxDecoration(
                  color: DashboardTheme.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(DashboardTheme.borderRadiusSmall),
                ),
                child: const Icon(
                  Icons.speed,
                  color: DashboardTheme.white,
                  size: 24,
                ),
              ),
            );
          },
        ),
        const SizedBox(width: DashboardTheme.spacing12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Métriques Temps Réel',
                style: DashboardTheme.titleMedium.copyWith(
                  color: DashboardTheme.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: DashboardTheme.spacing4),
              Text(
                'Mise à jour automatique',
                style: DashboardTheme.bodySmall.copyWith(
                  color: DashboardTheme.white.withOpacity(0.8),
                ),
              ),
            ],
          ),
        ),
        _buildRefreshIndicator(),
      ],
    );
  }

  Widget _buildRefreshIndicator() {
    return BlocBuilder<DashboardBloc, DashboardState>(
      builder: (context, state) {
        if (state is DashboardRefreshing) {
          return const SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(DashboardTheme.white),
            ),
          );
        }
        
        return GestureDetector(
          onTap: () {
            context.read<DashboardBloc>().add(RefreshDashboardData(
              organizationId: widget.organizationId,
              userId: widget.userId,
            ));
          },
          child: Container(
            padding: const EdgeInsets.all(DashboardTheme.spacing4),
            decoration: BoxDecoration(
              color: DashboardTheme.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(DashboardTheme.borderRadiusSmall),
            ),
            child: const Icon(
              Icons.refresh,
              color: DashboardTheme.white,
              size: 16,
            ),
          ),
        );
      },
    );
  }

  Widget _buildMetrics(DashboardEntity data) {
    return AnimatedBuilder(
      animation: _countAnimation,
      builder: (context, child) {
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: _buildMetricItem(
                    'Membres Actifs',
                    (data.stats.activeMembers * _countAnimation.value).round(),
                    data.stats.totalMembers,
                    Icons.people,
                    DashboardTheme.success,
                  ),
                ),
                const SizedBox(width: DashboardTheme.spacing16),
                Expanded(
                  child: _buildMetricItem(
                    'Engagement',
                    ((data.stats.engagementRate * 100) * _countAnimation.value).round(),
                    100,
                    Icons.favorite,
                    DashboardTheme.warning,
                    suffix: '%',
                  ),
                ),
              ],
            ),
            const SizedBox(height: DashboardTheme.spacing16),
            Row(
              children: [
                Expanded(
                  child: _buildMetricItem(
                    'Événements',
                    (data.stats.upcomingEvents * _countAnimation.value).round(),
                    data.stats.totalEvents,
                    Icons.event,
                    DashboardTheme.info,
                  ),
                ),
                const SizedBox(width: DashboardTheme.spacing16),
                Expanded(
                  child: _buildMetricItem(
                    'Croissance',
                    (data.stats.monthlyGrowth * _countAnimation.value),
                    null,
                    Icons.trending_up,
                    data.stats.hasGrowth ? DashboardTheme.success : DashboardTheme.error,
                    suffix: '%',
                    isDecimal: true,
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  Widget _buildMetricItem(
    String label,
    dynamic value,
    int? maxValue,
    IconData icon,
    Color color, {
    String suffix = '',
    bool isDecimal = false,
  }) {
    String displayValue;
    if (isDecimal) {
      displayValue = value.toStringAsFixed(1) + suffix;
    } else {
      displayValue = value.toString() + suffix;
    }

    return Container(
      padding: const EdgeInsets.all(DashboardTheme.spacing16),
      decoration: BoxDecoration(
        color: DashboardTheme.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(DashboardTheme.borderRadius),
        border: Border.all(
          color: DashboardTheme.white.withOpacity(0.2),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                icon,
                color: color,
                size: 20,
              ),
              const SizedBox(width: DashboardTheme.spacing8),
              Expanded(
                child: Text(
                  label,
                  style: DashboardTheme.bodySmall.copyWith(
                    color: DashboardTheme.white.withOpacity(0.8),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: DashboardTheme.spacing8),
          Text(
            displayValue,
            style: DashboardTheme.titleLarge.copyWith(
              color: DashboardTheme.white,
              fontWeight: FontWeight.bold,
              fontSize: 24,
            ),
          ),
          if (maxValue != null) ...[
            const SizedBox(height: DashboardTheme.spacing4),
            Text(
              'sur $maxValue',
              style: DashboardTheme.bodySmall.copyWith(
                color: DashboardTheme.white.withOpacity(0.6),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildLoadingMetrics() {
    return Column(
      children: [
        Row(
          children: [
            Expanded(child: _buildLoadingMetricItem()),
            const SizedBox(width: DashboardTheme.spacing16),
            Expanded(child: _buildLoadingMetricItem()),
          ],
        ),
        const SizedBox(height: DashboardTheme.spacing16),
        Row(
          children: [
            Expanded(child: _buildLoadingMetricItem()),
            const SizedBox(width: DashboardTheme.spacing16),
            Expanded(child: _buildLoadingMetricItem()),
          ],
        ),
      ],
    );
  }

  Widget _buildLoadingMetricItem() {
    return Container(
      height: 100,
      padding: const EdgeInsets.all(DashboardTheme.spacing16),
      decoration: BoxDecoration(
        color: DashboardTheme.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(DashboardTheme.borderRadius),
      ),
      child: const Center(
        child: CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(DashboardTheme.white),
        ),
      ),
    );
  }

  Widget _buildErrorMetrics() {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        color: DashboardTheme.error.withOpacity(0.1),
        borderRadius: BorderRadius.circular(DashboardTheme.borderRadius),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: DashboardTheme.error,
              size: 32,
            ),
            const SizedBox(height: DashboardTheme.spacing8),
            Text(
              'Erreur de chargement',
              style: DashboardTheme.bodyMedium.copyWith(
                color: DashboardTheme.error,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyMetrics() {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        color: DashboardTheme.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(DashboardTheme.borderRadius),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.speed,
              color: DashboardTheme.white.withOpacity(0.5),
              size: 32,
            ),
            const SizedBox(height: DashboardTheme.spacing8),
            Text(
              'Aucune donnée',
              style: DashboardTheme.bodyMedium.copyWith(
                color: DashboardTheme.white.withOpacity(0.7),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _refreshTimer?.cancel();
    _pulseController.dispose();
    _countController.dispose();
    super.dispose();
  }
}
