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: UnionFlowColors.background,
      appBar: _buildAppBar(context),
      drawer: DashboardDrawer(
        onNavigate: (route) => Navigator.of(context).pushNamed(route),
        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(24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
              // En-tête RH
              AnimatedFadeIn(
                delay: const Duration(milliseconds: 100),
                child: _buildUserHeader(),
              ),
              const SizedBox(height: 24),

                  // Stats RH (données backend réelles)
                  AnimatedSlideIn(
                    delay: const Duration(milliseconds: 200),
                    child: Row(
                      children: [
                        Expanded(
                          child: 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,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: 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,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),

                  AnimatedFadeIn(
                    delay: const Duration(milliseconds: 300),
                    child: Row(
                      children: [
                        Expanded(
                          child: UnionStatWidget(
                            label: 'Demandes',
                            value: '${stats?.pendingRequests ?? 0}',
                            icon: Icons.pending_actions,
                            color: UnionFlowColors.amber,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: 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: 24),

                  // Activité récente (données backend)
                  if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                    AnimatedFadeIn(
                      delay: const Duration(milliseconds: 400),
                      child: const Text(
                        'Activité RH Récente',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w700,
                          color: UnionFlowColors.textPrimary,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    AnimatedSlideIn(
                      delay: const Duration(milliseconds: 500),
                      child: Column(
                        children: dashboardData.recentActivities.take(4).map((activity) =>
                          Container(
                            margin: const EdgeInsets.only(bottom: 12),
                            padding: const EdgeInsets.all(14),
                            decoration: BoxDecoration(
                              color: UnionFlowColors.surface,
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(color: UnionFlowColors.border, width: 1),
                            ),
                            child: Row(
                              children: [
                                CircleAvatar(
                                  radius: 20,
                                  backgroundColor: activity.type == 'member'
                                      ? UnionFlowColors.success.withOpacity(0.2)
                                      : activity.type == 'contribution'
                                          ? UnionFlowColors.amber.withOpacity(0.2)
                                          : UnionFlowColors.terracotta.withOpacity(0.2),
                                  child: Icon(
                                    activity.type == 'member'
                                        ? Icons.person_add
                                        : activity.type == 'contribution'
                                            ? Icons.payment
                                            : Icons.event,
                                    size: 18,
                                    color: activity.type == 'member'
                                        ? UnionFlowColors.success
                                        : activity.type == 'contribution'
                                            ? UnionFlowColors.amber
                                            : UnionFlowColors.terracotta,
                                  ),
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        activity.title,
                                        style: const TextStyle(
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600,
                                          color: UnionFlowColors.textPrimary,
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      const SizedBox(height: 2),
                                      Text(
                                        activity.userName,
                                        style: const TextStyle(
                                          fontSize: 11,
                                          color: UnionFlowColors.textSecondary,
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ),
                                Text(
                                  activity.timeAgo,
                                  style: const TextStyle(
                                    fontSize: 11,
                                    color: UnionFlowColors.textTertiary,
                                  ),
                                ),
                              ],
                            ),
                          )
                        ).toList(),
                      ),
                    ),
                    const SizedBox(height: 24),
                  ],

                  // Répartition membres actifs/inactifs (données backend)
                  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: 24),

                  // Indicateurs RH
                  AnimatedFadeIn(
                    delay: const Duration(milliseconds: 600),
                child: const Text(
                  'Indicateurs Clés',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    color: UnionFlowColors.textPrimary,
                  ),
                ),
              ),
              const SizedBox(height: 16),

              AnimatedSlideIn(
                delay: const Duration(milliseconds: 700),
                child: Row(
                  children: [
                    Expanded(child: _buildMetric('Turnover', '5%', UnionFlowColors.success)),
                    const SizedBox(width: 12),
                    Expanded(child: _buildMetric('Absentéisme', '2%', UnionFlowColors.warning)),
                  ],
                ),
              ),
              const SizedBox(height: 12),

              AnimatedSlideIn(
                delay: const Duration(milliseconds: 800),
                child: Row(
                  children: [
                    Expanded(child: _buildMetric('Satisfaction', '87%', UnionFlowColors.gold)),
                    const SizedBox(width: 12),
                    Expanded(child: _buildMetric('Formation', '45h', UnionFlowColors.indigo)),
                  ],
                ),
              ),
              const SizedBox(height: 24),

              // Actions RH
              AnimatedFadeIn(
                delay: const Duration(milliseconds: 900),
                child: const Text(
                  'Gestion RH',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    color: UnionFlowColors.textPrimary,
                  ),
                ),
              ),
              const SizedBox(height: 16),

              AnimatedSlideIn(
                delay: const Duration(milliseconds: 1000),
                child: Row(
                  children: [
                    Expanded(
                      child: UnionActionButton(
                        label: 'Employés',
                        icon: Icons.people,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const MembersPageWrapper())),
                        backgroundColor: UnionFlowColors.unionGreen,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: UnionActionButton(
                        label: 'Congés',
                        icon: Icons.event_available,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const EventsPageWrapper())),
                        backgroundColor: UnionFlowColors.amber,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: UnionActionButton(
                        label: 'Paie',
                        icon: Icons.payments,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper())),
                        backgroundColor: UnionFlowColors.gold,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 12),

              AnimatedSlideIn(
                delay: const Duration(milliseconds: 1100),
                child: Row(
                  children: [
                    Expanded(
                      child: UnionActionButton(
                        label: 'Recrutement',
                        icon: Icons.person_add,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const MembersPageWrapper())),
                        backgroundColor: UnionFlowColors.info,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: UnionActionButton(
                        label: 'Formation',
                        icon: Icons.school,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const EventsPageWrapper())),
                        backgroundColor: UnionFlowColors.indigo,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: UnionActionButton(
                        label: 'Rapports',
                        icon: Icons.analytics,
                        onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ReportsPageWrapper())),
                        backgroundColor: UnionFlowColors.terracotta,
                      ),
                    ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      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),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              Text(
                'RH Manager',
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: UnionFlowColors.textPrimary),
      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),
      ],
    );
  }

  Widget _buildUserHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [UnionFlowColors.terracotta, UnionFlowColors.terracottaLight],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: const Border(
          top: BorderSide(color: UnionFlowColors.terracotta, width: 3),
        ),
        boxShadow: [
          BoxShadow(
            color: UnionFlowColors.terracotta.withOpacity(0.3),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 28,
            backgroundColor: Colors.white.withOpacity(0.3),
            child: const Text(
              'RH',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Gestionnaire RH',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Ressources Humaines & Talents',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.white.withOpacity(0.9),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text(
              'RH',
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.w800,
                color: UnionFlowColors.terracotta,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMetric(String label, String value, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: UnionFlowColors.surface,
        borderRadius: BorderRadius.circular(16),
        boxShadow: UnionFlowColors.softShadow,
      ),
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w800,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: UnionFlowColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }
}
