import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';

import 'package:unionflow_mobile_apps/core/network/api_client.dart';
import 'package:unionflow_mobile_apps/core/utils/logger.dart';
import '../../presentation/bloc/finance_state.dart';

/// Repository pour les données financières (cotisations, synthèse).
/// Appelle les endpoints /api/cotisations/mes-cotisations/*.
@lazySingleton
class FinanceRepository {
  final ApiClient _apiClient;

  FinanceRepository(this._apiClient);

  /// Synthèse des cotisations du membre connecté (GET /api/cotisations/mes-cotisations/synthese).
  Future<FinanceSummary> getFinancialSummary() async {
    try {
      final response = await _apiClient.get('/api/cotisations/mes-cotisations/synthese');
      final data = response.data as Map<String, dynamic>;
      final totalPayeAnnee = (data['totalPayeAnnee'] is num)
          ? (data['totalPayeAnnee'] as num).toDouble()
          : 0.0;
      final montantDu = (data['montantDu'] is num)
          ? (data['montantDu'] as num).toDouble()
          : 0.0;
      final epargneBalance = (data['epargneBalance'] is num)
          ? (data['epargneBalance'] as num).toDouble()
          : 0.0;
      return FinanceSummary(
        totalContributionsPaid: totalPayeAnnee,
        totalContributionsPending: montantDu,
        epargneBalance: epargneBalance,
      );
    } on DioException catch (e, st) {
      AppLogger.error('FinanceRepository: getFinancialSummary échoué', error: e, stackTrace: st);
      rethrow;
    } catch (e, st) {
      AppLogger.error('FinanceRepository: getFinancialSummary erreur inattendue', error: e, stackTrace: st);
      rethrow;
    }
  }

  /// Cotisations en attente du membre connecté (GET /api/cotisations/mes-cotisations/en-attente).
  Future<List<FinanceTransaction>> getTransactions() async {
    try {
      final response = await _apiClient.get('/api/cotisations/mes-cotisations/en-attente');
      final List<dynamic> data = response.data is List ? response.data as List : [];
      return data
          .map((json) => _transactionFromJson(json as Map<String, dynamic>))
          .toList();
    } on DioException catch (e, st) {
      AppLogger.error('FinanceRepository: getTransactions échoué', error: e, stackTrace: st);
      if (e.response?.statusCode == 404) return [];
      rethrow;
    }
  }

  static FinanceTransaction _transactionFromJson(Map<String, dynamic> json) {
    final id = json['id']?.toString() ?? '';
    final ref = json['numeroReference']?.toString() ?? '';
    final nomMembre = json['nomMembre']?.toString() ?? 'Cotisation';
    final montantDu = (json['montantDu'] is num)
        ? (json['montantDu'] as num).toDouble()
        : 0.0;
    final statutLibelle = json['statutLibelle']?.toString() ?? 'En attente';
    final dateEcheance = json['dateEcheance']?.toString();
    final dateStr = dateEcheance != null
        ? _parseDateToDisplay(dateEcheance)
        : '';
    return FinanceTransaction(
      id: id,
      title: nomMembre.isNotEmpty ? nomMembre : 'Cotisation $ref',
      date: dateStr,
      amount: montantDu,
      status: statutLibelle,
    );
  }

  static String _parseDateToDisplay(String isoDate) {
    try {
      final d = DateTime.parse(isoDate);
      return '${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year}';
    } catch (e) {
      AppLogger.warning('FinanceRepository: _parseDateToDisplay date invalide', tag: isoDate);
      return isoDate;
    }
  }
}
