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/dashboard_theme.dart';

/// Widget des activités récentes connecté au backend
class ConnectedRecentActivities extends StatelessWidget {
  final int maxItems;
  final VoidCallback? onSeeAll;

  const ConnectedRecentActivities({
    super.key,
    this.maxItems = 5,
    this.onSeeAll,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: DashboardTheme.cardDecoration,
      padding: const EdgeInsets.all(DashboardTheme.spacing16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          const SizedBox(height: DashboardTheme.spacing16),
          BlocBuilder<DashboardBloc, DashboardState>(
            builder: (context, state) {
              if (state is DashboardLoading) {
                return _buildLoadingList();
              } else if (state is DashboardLoaded || state is DashboardRefreshing) {
                final data = state is DashboardLoaded 
                    ? state.dashboardData 
                    : (state as DashboardRefreshing).dashboardData;
                return _buildActivitiesList(data.recentActivities);
              } else if (state is DashboardError) {
                return _buildErrorState(state.message);
              }
              return _buildEmptyState();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Row(
      children: [
        Container(
          padding: const EdgeInsets.all(DashboardTheme.spacing8),
          decoration: BoxDecoration(
            color: DashboardTheme.tealBlue.withOpacity(0.1),
            borderRadius: BorderRadius.circular(DashboardTheme.borderRadiusSmall),
          ),
          child: const Icon(
            Icons.history,
            color: DashboardTheme.tealBlue,
            size: 20,
          ),
        ),
        const SizedBox(width: DashboardTheme.spacing12),
        const Expanded(
          child: Text(
            'Activités récentes',
            style: DashboardTheme.titleMedium,
          ),
        ),
        if (onSeeAll != null)
          TextButton(
            onPressed: onSeeAll,
            child: Text(
              'Voir tout',
              style: DashboardTheme.bodyMedium.copyWith(
                color: DashboardTheme.royalBlue,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildActivitiesList(List<RecentActivityEntity> activities) {
    if (activities.isEmpty) {
      return _buildEmptyState();
    }

    final displayActivities = activities.take(maxItems).toList();

    return Column(
      children: displayActivities.asMap().entries.map((entry) {
        final index = entry.key;
        final activity = entry.value;
        final isLast = index == displayActivities.length - 1;

        return Column(
          children: [
            _buildActivityItem(activity),
            if (!isLast) const SizedBox(height: DashboardTheme.spacing12),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildActivityItem(RecentActivityEntity activity) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Avatar ou icône
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: _getActivityColor(activity.type).withOpacity(0.1),
            borderRadius: BorderRadius.circular(20),
          ),
          child: activity.userAvatar != null
              ? ClipRRect(
                  borderRadius: BorderRadius.circular(20),
                  child: Image.network(
                    activity.userAvatar!,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) => Icon(
                      _getActivityIcon(activity.type),
                      color: _getActivityColor(activity.type),
                      size: 20,
                    ),
                  ),
                )
              : Icon(
                  _getActivityIcon(activity.type),
                  color: _getActivityColor(activity.type),
                  size: 20,
                ),
        ),
        const SizedBox(width: DashboardTheme.spacing12),
        // Contenu
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                activity.title,
                style: DashboardTheme.bodyMedium.copyWith(
                  fontWeight: FontWeight.w600,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: DashboardTheme.spacing4),
              Text(
                activity.description,
                style: DashboardTheme.bodySmall,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: DashboardTheme.spacing4),
              Row(
                children: [
                  Text(
                    activity.userName,
                    style: DashboardTheme.bodySmall.copyWith(
                      fontWeight: FontWeight.w500,
                      color: DashboardTheme.royalBlue,
                    ),
                  ),
                  Text(
                    ' • ${activity.timeAgo}',
                    style: DashboardTheme.bodySmall,
                  ),
                ],
              ),
            ],
          ),
        ),
        // Action button si disponible
        if (activity.hasAction)
          IconButton(
            onPressed: () {
              // TODO: Naviguer vers l'action
            },
            icon: const Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: DashboardTheme.grey400,
            ),
          ),
      ],
    );
  }

  Widget _buildLoadingList() {
    return Column(
      children: List.generate(3, (index) => Column(
        children: [
          _buildLoadingItem(),
          if (index < 2) const SizedBox(height: DashboardTheme.spacing12),
        ],
      )),
    );
  }

  Widget _buildLoadingItem() {
    return Row(
      children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: DashboardTheme.grey200,
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        const SizedBox(width: DashboardTheme.spacing12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 16,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: DashboardTheme.grey200,
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              const SizedBox(height: DashboardTheme.spacing4),
              Container(
                height: 12,
                width: 200,
                decoration: BoxDecoration(
                  color: DashboardTheme.grey100,
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              const SizedBox(height: DashboardTheme.spacing4),
              Container(
                height: 12,
                width: 120,
                decoration: BoxDecoration(
                  color: DashboardTheme.grey100,
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildErrorState(String message) {
    return Center(
      child: Column(
        children: [
          const Icon(
            Icons.error_outline,
            color: DashboardTheme.error,
            size: 48,
          ),
          const SizedBox(height: DashboardTheme.spacing8),
          Text(
            'Erreur de chargement',
            style: DashboardTheme.bodyMedium.copyWith(
              color: DashboardTheme.error,
            ),
          ),
          const SizedBox(height: DashboardTheme.spacing4),
          Text(
            message,
            style: DashboardTheme.bodySmall,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        children: [
          const Icon(
            Icons.history,
            color: DashboardTheme.grey400,
            size: 48,
          ),
          const SizedBox(height: DashboardTheme.spacing8),
          Text(
            'Aucune activité récente',
            style: DashboardTheme.bodyMedium.copyWith(
              color: DashboardTheme.grey500,
            ),
          ),
          const SizedBox(height: DashboardTheme.spacing4),
          const Text(
            'Les activités apparaîtront ici',
            style: DashboardTheme.bodySmall,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  IconData _getActivityIcon(String type) {
    switch (type.toLowerCase()) {
      case 'member':
        return Icons.person_add;
      case 'event':
        return Icons.event;
      case 'contribution':
        return Icons.payment;
      case 'organization':
        return Icons.business;
      case 'system':
        return Icons.settings;
      default:
        return Icons.notifications;
    }
  }

  Color _getActivityColor(String type) {
    switch (type.toLowerCase()) {
      case 'member':
        return DashboardTheme.success;
      case 'event':
        return DashboardTheme.info;
      case 'contribution':
        return DashboardTheme.tealBlue;
      case 'organization':
        return DashboardTheme.royalBlue;
      case 'system':
        return DashboardTheme.warning;
      default:
        return DashboardTheme.grey500;
    }
  }
}
