import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../domain/entities/dashboard_entity.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../../../../shared/design_system/unionflow_design_system.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: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [AppColors.primaryDark, AppColors.primary],
        ),
        borderRadius: BorderRadius.circular(10),
      ),
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          const SizedBox(height: 10),
          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(6),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Icon(
                  Icons.speed_outlined,
                  color: Colors.white,
                  size: 16,
                ),
              ),
            );
          },
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'MÉTRIQUES TEMPS RÉEL',
                style: AppTypography.actionText.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                'Mise à jour automatique (5 min)',
                style: AppTypography.subtitleSmall.copyWith(
                  color: Colors.white.withOpacity(0.8),
                  fontSize: 10,
                ),
              ),
            ],
          ),
        ),
        _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>(Colors.white),
            ),
          );
        }
        
        return GestureDetector(
          onTap: () {
            context.read<DashboardBloc>().add(RefreshDashboardData(
              organizationId: widget.organizationId,
              userId: widget.userId,
            ));
          },
          child: Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(4),
            ),
            child: const Icon(
              Icons.refresh_outlined,
              color: Colors.white,
              size: 14,
            ),
          ),
        );
      },
    );
  }

  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_outline,
                    AppColors.success,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildMetricItem(
                    'Engagement',
                    ((data.stats.engagementRate * 100) * _countAnimation.value).round(),
                    100,
                    Icons.favorite,
                    AppColors.warning,
                    suffix: '%',
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: _buildMetricItem(
                    'Événements',
                    (data.stats.upcomingEvents * _countAnimation.value).round(),
                    data.stats.totalEvents,
                    Icons.event,
                    AppColors.info,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: _buildMetricItem(
                    'Croissance',
                    (data.stats.monthlyGrowth * _countAnimation.value),
                    null,
                    Icons.trending_up,
                    data.stats.hasGrowth ? AppColors.success : AppColors.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(8),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color: Colors.white.withOpacity(0.2),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                icon,
                color: color,
                size: 14,
              ),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  label.toUpperCase(),
                  style: AppTypography.badgeText.copyWith(
                    color: Colors.white.withOpacity(0.8),
                    fontSize: 8,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            displayValue,
            style: AppTypography.headerSmall.copyWith(
              color: Colors.white,
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          if (maxValue != null) ...[
            const SizedBox(height: 2),
            Text(
              'sur $maxValue',
              style: AppTypography.subtitleSmall.copyWith(
                color: Colors.white.withOpacity(0.6),
                fontSize: 8,
              ),
            ),
          ],
        ],
      ),
    );
  }

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

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

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

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

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