import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../widgets/shared/mini_header_bar.dart';
import '../../shared/widgets/core_card.dart';
import '../widgets/shared/mini_metric_widget.dart';
import '../../shared/widgets/core_shimmer.dart';
import '../../shared/widgets/info_badge.dart';
import '../../shared/design_system/tokens/app_typography.dart';
import '../../shared/design_system/tokens/app_colors.dart';

import '../../core/di/injection.dart';
import '../../features/dashboard/presentation/bloc/finance_bloc.dart';
import '../../features/dashboard/presentation/bloc/finance_event.dart';
import '../../features/dashboard/presentation/bloc/finance_state.dart';

/// UnionFlow Mobile - Onglet Finances (Mode DRY & Ultra-compact)
/// Évite les gros blocs de texte, privilégie les métriques denses.
class FinancePage extends StatelessWidget {
  const FinancePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => getIt<FinanceBloc>()..add(LoadFinanceRequested()),
      child: const _FinanceView(),
    );
  }
}

class _FinanceView extends StatelessWidget {
  const _FinanceView();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const MiniHeaderBar(title: 'Finances'),
      body: BlocBuilder<FinanceBloc, FinanceState>(
        builder: (context, state) {
          if (state is FinanceInitial || state is FinanceLoading) {
            return const Padding(
              padding: EdgeInsets.all(8.0),
              child: CoreShimmer(itemCount: 4),
            );
          }

          if (state is FinanceError) {
            return Center(
              child: Text(
                state.message,
                style: AppTypography.bodyTextSmall.copyWith(color: AppColors.error),
              ),
            );
          }

          if (state is FinanceLoaded) {
            return CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Résumé Compact
                        CoreCard(
                          child: IntrinsicHeight(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Expanded(
                                  child: MiniMetricWidget(
                                    label: 'Payées',
                                    value: '${state.summary.totalContributionsPaid} F',
                                    valueColor: AppColors.success,
                                    alignment: CrossAxisAlignment.center,
                                  ),
                                ),
                                const VerticalDivider(color: AppColors.lightBorder),
                                Expanded(
                                  child: MiniMetricWidget(
                                    label: 'En attente',
                                    value: '${state.summary.totalContributionsPending} F',
                                    valueColor: AppColors.warning,
                                    alignment: CrossAxisAlignment.center,
                                  ),
                                ),
                                const VerticalDivider(color: AppColors.lightBorder),
                                Expanded(
                                  child: MiniMetricWidget(
                                    label: 'Épargne',
                                    value: '${state.summary.epargneBalance} F',
                                    alignment: CrossAxisAlignment.center,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        
                        const SizedBox(height: 16),
                        Padding(
                          padding: const EdgeInsets.only(left: 4, bottom: 8),
                          child: Text(
                            'HISTORIQUE',
                            style: AppTypography.badgeText.copyWith(
                              color: Theme.of(context).brightness == Brightness.dark 
                                  ? AppColors.textSecondaryDark 
                                  : AppColors.textSecondaryLight,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                
                // Liste des transactions (Recycle CoreCard)
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (context, index) {
                      final tx = state.transactions[index];
                      final isPaid = tx.status == 'Payé';
                      
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: CoreCard(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    tx.title,
                                    style: AppTypography.actionText,
                                  ),
                                  Text(
                                    tx.date,
                                    style: AppTypography.subtitleSmall,
                                  ),
                                ],
                              ),
                              Row(
                                children: [
                                  Text(
                                    '${tx.amount} F',
                                    style: AppTypography.actionText,
                                  ),
                                  const SizedBox(width: 8),
                                  InfoBadge(
                                    text: tx.status,
                                    backgroundColor: isPaid ? AppColors.success.withOpacity(0.1) : AppColors.warning.withOpacity(0.1),
                                    textColor: isPaid ? AppColors.success : AppColors.warning,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                    childCount: state.transactions.length,
                  ),
                ),
              ],
            );
          }

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