import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../widgets/dashboard_drawer.dart';
import '../../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../../../members/presentation/pages/members_page_wrapper.dart';
import '../../../../events/presentation/pages/events_page_wrapper.dart';
import '../../../../contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../../reports/presentation/pages/reports_page_wrapper.dart';
import '../../../../notifications/presentation/pages/notifications_page_wrapper.dart';

/// Dashboard RH Manager - Design UnionFlow Gestion des Ressources Humaines
class HRManagerDashboard extends StatelessWidget {
  const HRManagerDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: _buildAppBar(context),
      drawer: DashboardDrawer(
        onLogout: () => context.read<AuthBloc>().add(const AuthLogoutRequested()),
      ),
      body: AfricanPatternBackground(
        child: BlocBuilder<DashboardBloc, DashboardState>(
          builder: (context, dashboardState) {
            if (dashboardState is DashboardLoading) {
              return const Center(
                child: CircularProgressIndicator(color: UnionFlowColors.terracotta),
              );
            }

            final dashboardData = (dashboardState is DashboardLoaded)
                ? dashboardState.dashboardData
                : null;
            final stats = dashboardData?.stats;

            return SingleChildScrollView(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // En-tête RH
                  AnimatedFadeIn(
                    delay: const Duration(milliseconds: 100),
                    child: UserIdentityCard(
                      initials: 'RH',
                      name: 'Gestionnaire RH',
                      subtitle: 'Ressources Humaines & Talents',
                      badgeLabel: 'RH',
                      gradient: LinearGradient(
                        colors: [UnionFlowColors.terracotta, UnionFlowColors.terracottaLight],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      accentColor: UnionFlowColors.terracotta,
                    ),
                  ),
                  const SizedBox(height: 12),

                  // Stats RH
                  AnimatedSlideIn(
                    delay: const Duration(milliseconds: 200),
                    child: GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: 2,
                      mainAxisSpacing: 6,
                      crossAxisSpacing: 6,
                      childAspectRatio: 2.0,
                      children: [
                        UnionStatWidget(
                          label: 'Membres',
                          value: '${stats?.totalMembers ?? 0}',
                          icon: Icons.people_outlined,
                          color: UnionFlowColors.unionGreen,
                          trend: stats != null && stats.monthlyGrowth > 0
                              ? '+${stats.monthlyGrowth.toStringAsFixed(1)}%'
                              : null,
                          isTrendUp: (stats?.monthlyGrowth ?? 0) > 0,
                        ),
                        UnionStatWidget(
                          label: 'Actifs',
                          value: '${stats?.activeMembers ?? 0}',
                          icon: Icons.person,
                          color: UnionFlowColors.success,
                          trend: stats != null && stats.totalMembers > 0
                              ? '${((stats.activeMembers / stats.totalMembers) * 100).toStringAsFixed(0)}%'
                              : null,
                          isTrendUp: true,
                        ),
                        UnionStatWidget(
                          label: 'Demandes',
                          value: '${stats?.pendingRequests ?? 0}',
                          icon: Icons.pending_actions,
                          color: UnionFlowColors.amber,
                        ),
                        UnionStatWidget(
                          label: 'Événements',
                          value: '${stats?.upcomingEvents ?? 0}',
                          icon: Icons.event,
                          color: UnionFlowColors.info,
                          trend: stats?.totalEvents != null ? '${stats!.totalEvents} total' : null,
                          isTrendUp: true,
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),

                  // Activité récente
                  if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                    AnimatedFadeIn(
                      delay: const Duration(milliseconds: 400),
                      child: const UFSectionHeader('Activité RH Récente'),
                    ),
                    const SizedBox(height: 8),
                    AnimatedSlideIn(
                      delay: const Duration(milliseconds: 500),
                      child: Column(
                        children: dashboardData.recentActivities.take(4).map((activity) =>
                          DashboardActivityRow(
                            title: activity.title,
                            description: activity.description,
                            timeAgo: activity.timeAgo,
                            icon: DashboardActivityRow.iconFor(activity.type),
                            color: DashboardActivityRow.colorFor(activity.type),
                          ),
                        ).toList(),
                      ),
                    ),
                    const SizedBox(height: 12),
                  ],

                  // Répartition membres actifs/inactifs
                  if (stats != null && stats.totalMembers > 0) ...[
                    AnimatedFadeIn(
                      delay: const Duration(milliseconds: 500),
                      child: UnionPieChart(
                        title: 'Activité des Membres',
                        subtitle: '${stats.totalMembers} membres au total',
                        sections: [
                          UnionPieChartSection.create(
                            value: stats.activeMembers.toDouble(),
                            color: UnionFlowColors.success,
                            title: '${((stats.activeMembers / stats.totalMembers) * 100).toStringAsFixed(0)}%\nActifs',
                          ),
                          UnionPieChartSection.create(
                            value: (stats.totalMembers - stats.activeMembers).toDouble(),
                            color: UnionFlowColors.textTertiary,
                            title: '${(((stats.totalMembers - stats.activeMembers) / stats.totalMembers) * 100).toStringAsFixed(0)}%\nInactifs',
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 12),
                  ],

                  // Indicateurs Clés
                  AnimatedFadeIn(
                    delay: const Duration(milliseconds: 600),
                    child: const UFSectionHeader('Indicateurs Clés'),
                  ),
                  const SizedBox(height: 8),

                  AnimatedSlideIn(
                    delay: const Duration(milliseconds: 700),
                    child: GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: 2,
                      mainAxisSpacing: 6,
                      crossAxisSpacing: 6,
                      childAspectRatio: 2.0,
                      children: [
                        UnionStatWidget(label: 'Turnover', value: '5%', icon: Icons.swap_horiz, color: UnionFlowColors.success),
                        UnionStatWidget(label: 'Absentéisme', value: '2%', icon: Icons.event_busy, color: UnionFlowColors.warning),
                        UnionStatWidget(label: 'Satisfaction', value: '87%', icon: Icons.sentiment_satisfied, color: UnionFlowColors.gold),
                        UnionStatWidget(label: 'Formation', value: '45h', icon: Icons.school, color: UnionFlowColors.indigo),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),

                  // Actions RH
                  AnimatedFadeIn(
                    delay: const Duration(milliseconds: 900),
                    child: const UFSectionHeader('Gestion RH'),
                  ),
                  const SizedBox(height: 8),

                  AnimatedSlideIn(
                    delay: const Duration(milliseconds: 1000),
                    child: GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: 3,
                      mainAxisSpacing: 6,
                      crossAxisSpacing: 6,
                      childAspectRatio: 2.8,
                      children: [
                        UnionActionButton(
                          label: 'Employés',
                          icon: Icons.people,
                          iconColor: UnionFlowColors.unionGreen,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const MembersPageWrapper())),
                        ),
                        UnionActionButton(
                          label: 'Congés',
                          icon: Icons.event_available,
                          iconColor: UnionFlowColors.amber,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EventsPageWrapper())),
                        ),
                        UnionActionButton(
                          label: 'Paie',
                          icon: Icons.payments,
                          iconColor: UnionFlowColors.gold,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ContributionsPageWrapper())),
                        ),
                        UnionActionButton(
                          label: 'Recrutement',
                          icon: Icons.person_add,
                          iconColor: UnionFlowColors.info,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const MembersPageWrapper())),
                        ),
                        UnionActionButton(
                          label: 'Formation',
                          icon: Icons.school,
                          iconColor: UnionFlowColors.indigo,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EventsPageWrapper())),
                        ),
                        UnionActionButton(
                          label: 'Rapports',
                          icon: Icons.analytics,
                          iconColor: UnionFlowColors.terracotta,
                          onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ReportsPageWrapper())),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: Theme.of(context).colorScheme.surface,
      elevation: 0,
      scrolledUnderElevation: 1,
      shadowColor: Theme.of(context).colorScheme.outline.withOpacity(0.2),
      title: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [UnionFlowColors.terracotta, UnionFlowColors.terracottaLight],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.center,
            child: const Text('H', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 18)),
          ),
          const SizedBox(width: 12),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('UnionFlow', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Theme.of(context).colorScheme.onSurface)),
              Text('RH Manager', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w400, color: Theme.of(context).colorScheme.onSurfaceVariant)),
            ],
          ),
        ],
      ),
      iconTheme: IconThemeData(color: Theme.of(context).colorScheme.onSurface),
      actions: [
        UnionExportButton(
          onExport: (_) => Navigator.of(context).push(
            MaterialPageRoute<void>(builder: (_) => const ReportsPageWrapper()),
          ),
        ),
        const SizedBox(width: 8),
        UnionNotificationBadge(
          count: 6,
          child: IconButton(
            icon: const Icon(Icons.notifications_outlined),
            color: UnionFlowColors.textPrimary,
            onPressed: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const NotificationsPageWrapper())),
          ),
        ),
        const SizedBox(width: 8),
      ],
    );
  }
}
