import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/dashboard_bloc.dart';
import '../widgets/connected/connected_stats_card.dart';
import '../widgets/connected/connected_recent_activities.dart';
import '../widgets/connected/connected_upcoming_events.dart';
import '../../../../shared/design_system/dashboard_theme.dart';

/// Page dashboard connectée au backend
class ConnectedDashboardPage extends StatefulWidget {
  final String organizationId;
  final String userId;

  const ConnectedDashboardPage({
    super.key,
    required this.organizationId,
    required this.userId,
  });

  @override
  State<ConnectedDashboardPage> createState() => _ConnectedDashboardPageState();
}

class _ConnectedDashboardPageState extends State<ConnectedDashboardPage> {
  @override
  void initState() {
    super.initState();
    // Charger les données du dashboard
    context.read<DashboardBloc>().add(LoadDashboardData(
      organizationId: widget.organizationId,
      userId: widget.userId,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: DashboardTheme.grey50,
      appBar: AppBar(
        title: const Text('Dashboard'),
        backgroundColor: DashboardTheme.royalBlue,
        foregroundColor: DashboardTheme.white,
        elevation: 0,
      ),
      body: BlocBuilder<DashboardBloc, DashboardState>(
        builder: (context, state) {
          if (state is DashboardLoading) {
            return const Center(
              child: CircularProgressIndicator(
                color: DashboardTheme.royalBlue,
              ),
            );
          }

          if (state is DashboardError) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    size: 64,
                    color: DashboardTheme.error,
                  ),
                  const SizedBox(height: DashboardTheme.spacing16),
                  const Text(
                    'Erreur de chargement',
                    style: DashboardTheme.titleMedium,
                  ),
                  const SizedBox(height: DashboardTheme.spacing8),
                  Text(
                    state.message,
                    style: DashboardTheme.bodyMedium,
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: DashboardTheme.spacing24),
                  ElevatedButton(
                    onPressed: () {
                      context.read<DashboardBloc>().add(LoadDashboardData(
                        organizationId: widget.organizationId,
                        userId: widget.userId,
                      ));
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: DashboardTheme.royalBlue,
                      foregroundColor: DashboardTheme.white,
                    ),
                    child: const Text('Réessayer'),
                  ),
                ],
              ),
            );
          }

          if (state is DashboardLoaded) {
            return RefreshIndicator(
              onRefresh: () async {
                context.read<DashboardBloc>().add(LoadDashboardData(
                  organizationId: widget.organizationId,
                  userId: widget.userId,
                ));
              },
              color: DashboardTheme.royalBlue,
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: const EdgeInsets.all(DashboardTheme.spacing16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Statistiques
                    Row(
                      children: [
                        Expanded(
                          child: ConnectedStatsCard(
                            title: 'Membres',
                            icon: Icons.people,
                            valueExtractor: (stats) => stats.totalMembers.toString(),
                            subtitleExtractor: (stats) => '${stats.activeMembers} actifs',
                          ),
                        ),
                        const SizedBox(width: DashboardTheme.spacing16),
                        Expanded(
                          child: ConnectedStatsCard(
                            title: 'Événements',
                            icon: Icons.event,
                            valueExtractor: (stats) => stats.totalEvents.toString(),
                            subtitleExtractor: (stats) => '${stats.upcomingEvents} à venir',
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: DashboardTheme.spacing24),
                    
                    // Activités récentes et événements à venir
                    const Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: ConnectedRecentActivities(),
                        ),
                        SizedBox(width: DashboardTheme.spacing16),
                        Expanded(
                          child: ConnectedUpcomingEvents(),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          }

          return const SizedBox.shrink();
        },
      ),
    );
  }
}
