/// Page des approbations en attente
library pending_approvals_page;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/di/injection_container.dart';
import 'package:intl/intl.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../domain/entities/transaction_approval.dart';
import '../bloc/approval_bloc.dart';
import '../bloc/approval_event.dart';
import '../bloc/approval_state.dart';
import '../widgets/approve_dialog.dart';
import '../widgets/reject_dialog.dart';

class PendingApprovalsPage extends StatelessWidget {
  final String? organizationId;

  const PendingApprovalsPage({
    super.key,
    this.organizationId,
  });

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<ApprovalBloc>()
        ..add(LoadPendingApprovals(organizationId: organizationId)),
      child: _PendingApprovalsView(organizationId: organizationId),
    );
  }
}

class _PendingApprovalsView extends StatelessWidget {
  final String? organizationId;

  const _PendingApprovalsView({this.organizationId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorTokens.background,
      appBar: UFAppBar(
        title: 'APPROBATIONS EN ATTENTE',
        automaticallyImplyLeading: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              context.read<ApprovalBloc>().add(
                    RefreshApprovals(organizationId: organizationId),
                  );
            },
          ),
        ],
      ),
      body: BlocConsumer<ApprovalBloc, ApprovalState>(
        listener: (context, state) {
          if (state is TransactionApproved) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: AppColors.success,
              ),
            );
            context.read<ApprovalBloc>().add(
                  RefreshApprovals(organizationId: organizationId),
                );
          } else if (state is TransactionRejected) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: AppColors.warning,
              ),
            );
            context.read<ApprovalBloc>().add(
                  RefreshApprovals(organizationId: organizationId),
                );
          } else if (state is ApprovalError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: AppColors.error,
              ),
            );
          }
        },
        builder: (context, state) {
          if (state is ApprovalsLoading || state is ApprovalActionInProgress) {
            return const Center(child: CircularProgressIndicator());
          }

          if (state is ApprovalsEmpty) {
            return _buildEmptyState();
          }

          if (state is ApprovalsLoaded) {
            return _buildApprovalsList(context, state.approvals);
          }

          if (state is ApprovalError) {
            return _buildErrorState(context, state.message);
          }

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

  Widget _buildApprovalsList(
    BuildContext context,
    List<TransactionApproval> approvals,
  ) {
    return RefreshIndicator(
      onRefresh: () async {
        context.read<ApprovalBloc>().add(
              RefreshApprovals(organizationId: organizationId),
            );
      },
      child: ListView.separated(
        padding: const EdgeInsets.all(SpacingTokens.md),
        itemCount: approvals.length,
        separatorBuilder: (_, __) => const SizedBox(height: SpacingTokens.md),
        itemBuilder: (context, index) {
          final approval = approvals[index];
          return _ApprovalCard(
            approval: approval,
            onApprove: () => _showApproveDialog(context, approval),
            onReject: () => _showRejectDialog(context, approval),
          );
        },
      ),
    );
  }

  void _showApproveDialog(BuildContext context, TransactionApproval approval) {
    showDialog(
      context: context,
      builder: (dialogContext) => BlocProvider.value(
        value: context.read<ApprovalBloc>(),
        child: ApproveDialog(approval: approval),
      ),
    );
  }

  void _showRejectDialog(BuildContext context, TransactionApproval approval) {
    showDialog(
      context: context,
      builder: (dialogContext) => BlocProvider.value(
        value: context.read<ApprovalBloc>(),
        child: RejectDialog(approval: approval),
      ),
    );
  }

  Widget _buildErrorState(BuildContext context, String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 80,
            color: AppColors.error.withOpacity(0.5),
          ),
          const SizedBox(height: SpacingTokens.lg),
          Text(
            message,
            style: AppTypography.headerSmall.copyWith(
              color: AppColors.textSecondaryLight,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: SpacingTokens.lg),
          UFPrimaryButton(
            label: 'Réessayer',
            onPressed: () {
              context.read<ApprovalBloc>().add(
                    LoadPendingApprovals(organizationId: organizationId),
                  );
            },
            icon: Icons.refresh,
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.check_circle_outline,
            size: 80,
            color: AppColors.success.withOpacity(0.5),
          ),
          const SizedBox(height: SpacingTokens.lg),
          Text(
            'Aucune approbation en attente',
            style: AppTypography.headerSmall.copyWith(
              color: AppColors.textSecondaryLight,
            ),
          ),
          const SizedBox(height: SpacingTokens.sm),
          Text(
            'Toutes les transactions sont approuvées',
            style: AppTypography.bodyTextSmall.copyWith(
              color: AppColors.textSecondaryLight,
            ),
          ),
        ],
      ),
    );
  }

}

class _ApprovalCard extends StatelessWidget {
  final TransactionApproval approval;
  final VoidCallback onApprove;
  final VoidCallback onReject;

  const _ApprovalCard({
    required this.approval,
    required this.onApprove,
    required this.onReject,
  });

  String _getTransactionTypeLabel(TransactionType type) {
    switch (type) {
      case TransactionType.contribution:
        return 'Cotisation';
      case TransactionType.deposit:
        return 'Dépôt';
      case TransactionType.withdrawal:
        return 'Retrait';
      case TransactionType.transfer:
        return 'Transfert';
      case TransactionType.solidarity:
        return 'Solidarité';
      case TransactionType.event:
        return 'Événement';
      case TransactionType.other:
        return 'Autre';
    }
  }

  Color _getLevelColor(ApprovalLevel level) {
    switch (level) {
      case ApprovalLevel.none:
        return AppColors.textSecondaryLight;
      case ApprovalLevel.level1:
        return AppColors.brandGreen;
      case ApprovalLevel.level2:
        return AppColors.warning;
      case ApprovalLevel.level3:
        return AppColors.error;
    }
  }

  @override
  Widget build(BuildContext context) {
    final currencyFormat = NumberFormat.currency(symbol: approval.currency);

    return Container(
      padding: const EdgeInsets.all(SpacingTokens.md),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(SpacingTokens.radiusMd),
        border: Border.all(color: AppColors.lightBorder),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0A000000),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  _getTransactionTypeLabel(approval.transactionType),
                  style: AppTypography.actionText,
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 8,
                  vertical: 4,
                ),
                decoration: BoxDecoration(
                  color: _getLevelColor(approval.requiredLevel).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(SpacingTokens.radiusSm),
                ),
                child: Text(
                  'Niveau ${approval.requiredApprovals}',
                  style: AppTypography.badgeText.copyWith(
                    color: _getLevelColor(approval.requiredLevel),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: SpacingTokens.sm),
          Text(
            currencyFormat.format(approval.amount),
            style: AppTypography.headerSmall.copyWith(
              color: AppColors.primaryGreen,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: SpacingTokens.sm),
          Row(
            children: [
              Icon(
                Icons.person_outline,
                size: 16,
                color: AppColors.textSecondaryLight,
              ),
              const SizedBox(width: 4),
              Expanded(
                child: Text(
                  'Demandé par ${approval.requesterName}',
                  style: AppTypography.subtitleSmall,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            children: [
              Icon(
                Icons.access_time,
                size: 16,
                color: AppColors.textSecondaryLight,
              ),
              const SizedBox(width: 4),
              Text(
                DateFormat('dd/MM/yyyy HH:mm').format(approval.createdAt),
                style: AppTypography.subtitleSmall,
              ),
            ],
          ),
          if (approval.approvers.isNotEmpty) ...[
            const SizedBox(height: SpacingTokens.sm),
            const Divider(),
            const SizedBox(height: SpacingTokens.sm),
            Text(
              'Approbations : ${approval.approvalCount}/${approval.requiredApprovals}',
              style: AppTypography.subtitleSmall.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
          const SizedBox(height: SpacingTokens.md),
          Row(
            children: [
              Expanded(
                child: UFSecondaryButton(
                  label: 'Rejeter',
                  onPressed: onReject,
                  icon: Icons.close,
                ),
              ),
              const SizedBox(width: SpacingTokens.sm),
              Expanded(
                child: UFPrimaryButton(
                  label: 'Approuver',
                  onPressed: onApprove,
                  icon: Icons.check,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
