import 'package:equatable/equatable.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/domains/charts/models/month_totals.dart';
import 'package:krezus/domains/transaction/models/transaction_line.dart';
import 'package:krezus/domains/charts/models/chart_item.dart';
import 'package:krezus/repositories/metadata/metadata_repository.dart';
import 'package:krezus/repositories/metadata/models/category.dart';
import 'package:krezus/repositories/transactions/models/transaction.dart';
import 'package:krezus/repositories/transactions/transactions_repository.dart';

part 'chart_event.dart';
part 'chart_state.dart';

class ChartBloc extends Bloc<ChartEvent, ChartState> {
  final MetadataRepository _metadataRepository;
  final TransactionsRepository _transactionsRepository;

  ChartBloc({required MetadataRepository metadataRepository, required TransactionsRepository transactionsRepository}) : 
    _metadataRepository = metadataRepository, _transactionsRepository = transactionsRepository, super(const ChartState()) {

    on<ChartTransactionsLoad>(_onChartTransactionsLoad);
    on<ChartCategoriesLoad>(_onChartCategoriesLoad);
    on<ChartNextYear>(_onNextYear);
    on<ChartPreviousYear>(_onPreviousYear);

    _transactionsRepository
      .getTransactionsStream()
      .listen((transactions) => add(ChartTransactionsLoad(transactions)));

    _metadataRepository
      .getCategoriesStream()
      .listen((categories) => add(ChartCategoriesLoad(categories)));
  }

  _onChartTransactionsLoad(ChartTransactionsLoad event, Emitter<ChartState> emit) {
    ChartState localState = state.copyWith(transactions: event.transactions);
    emit(_computeStateStats(localState));
  }

  _onChartCategoriesLoad(ChartCategoriesLoad event, Emitter<ChartState> emit) {
    ChartState localState = state.copyWith(categories: Map.fromEntries(event.categories.map((category) => MapEntry(category.label, category))));
    emit(_computeStateStats(localState));
  }

  _onNextYear(ChartNextYear event, Emitter<ChartState> emit) {
    if (state.lastDate!.year >= state.currentYear + 1) {
      ChartState localState = state.copyWith(currentYear: state.currentYear + 1);
      emit(_computeStateScopedStats(localState));
    }
  }

  _onPreviousYear(ChartPreviousYear event, Emitter<ChartState> emit) {
    if (state.firstDate!.year <= state.currentYear - 1) {
      ChartState localState = state.copyWith(currentYear: state.currentYear - 1);
      emit(_computeStateScopedStats(localState));
    }
  }

  ChartState _computeStateStats(ChartState state) {
    double globalTotal = 0;
    Map<String, double> accountsTotals = <String, double>{};
    List<TransactionLine> transactionsLines = [];

    Map<String, double> categoriesTotals = {};
    List<FlSpot> monthlyTotals = [];
    Map<String, Map<String, double>> categoriesMonthlyTotals = {};

    DateTime firstDate = DateTime.now();
    DateTime lastDate = DateTime.fromMicrosecondsSinceEpoch(0);

    for(var transaction in state.transactions) {
      double subTotal = globalTotal + transaction.value;
      globalTotal = subTotal;

      double accountTotal = accountsTotals[transaction.account] ?? 0;
      accountTotal += transaction.value;
      accountsTotals[transaction.account] = accountTotal;

      TransactionLine transactionLine = TransactionLine(transaction: transaction, subTotal: subTotal);

      transactionsLines.add(transactionLine);
      monthlyTotals.add(FlSpot(transactionLine.transaction.date.microsecondsSinceEpoch.toDouble(), transactionLine.subTotal));

      if (firstDate.compareTo(transaction.date) > 0) {
        firstDate = transaction.date;
      }

      if (lastDate.compareTo(transaction.date) < 0) {
        lastDate = transaction.date;
      }

      double categoryTotal = categoriesTotals[transaction.category] ?? 0;
      categoryTotal += transaction.value;
      categoriesTotals[transaction.category] = categoryTotal;
    }

    return _computeStateScopedStats(state.copyWith(
      transactionsLines: transactionsLines,
      globalTotal: globalTotal,
      accountsTotals: accountsTotals,
      categoriesTotals: categoriesTotals,
      monthlyTotals: monthlyTotals,
      categoriesMonthlyTotals: categoriesMonthlyTotals,
      firstDate: firstDate,
      lastDate: lastDate,
      currentYear: DateTime.now().year,
    ));
  }

  ChartState _computeStateScopedStats(ChartState state) {
    double globalTotal = 0;
    double scoppedTotal = 0;
    List<ChartItem> scopedCategoriesPositiveTotals = [];
    List<ChartItem> scopedCategoriesNegativeTotals = [];
    Map<int, FlSpot> scopedMonthlyTotalsMap = {};
    Map<int, MonthTotals> scopedCategoriesMonthlyTotals = {};

    Map<int, double> scopedMonthlyPostitiveTotals = {};
    Map<int, double> scopedMonthlyNegativeTotals = {};

    for(var transaction in state.transactions) {
      globalTotal += transaction.value;
      double subTotal = globalTotal;

      if (transaction.date.year != state.currentYear) {
        continue;
      }

      scoppedTotal += transaction.value;

      TransactionLine transactionLine = TransactionLine(transaction: transaction, subTotal: subTotal);

      DateTime transactionDate = transactionLine.transaction.date;
      int transactionDateDay = transactionDate.difference(DateTime(transactionDate.year,1,1)).inDays + 1;

      scopedMonthlyTotalsMap[transactionDateDay] = FlSpot(transactionDateDay.toDouble(), transactionLine.subTotal);

      final category = state.categories[transaction.category];
      if (category == null || category.transfert) {
        continue;
      }

      MonthTotals? categoryMonthTotal = scopedCategoriesMonthlyTotals[transaction.date.month];
      if (categoryMonthTotal == null) {
        categoryMonthTotal = MonthTotals(negatives: {}, positives: {});
        scopedCategoriesMonthlyTotals[transaction.date.month] = categoryMonthTotal;
      }

      if (transaction.value >= 0) {
        ChartItem? chartItem = scopedCategoriesPositiveTotals.firstWhere(
          (item) => item.label == transaction.category,
          orElse: () {
            ChartItem newChartItem = ChartItem(label: transaction.category, value: 0);
            scopedCategoriesPositiveTotals.add(newChartItem);
            return newChartItem;
          }
        );
        chartItem.value += transaction.value;

        scopedMonthlyPostitiveTotals[transaction.date.month] = transaction.value + (scopedMonthlyPostitiveTotals[transaction.date.month] ?? 0);
        categoryMonthTotal.positives[transaction.category] = transaction.value.abs() + (categoryMonthTotal.positives[transaction.category] ?? 0);
      }

      if (transaction.value < 0) {
        ChartItem? chartItem = scopedCategoriesNegativeTotals.firstWhere(
          (item) => item.label == transaction.category,
          orElse: () {
            ChartItem newChartItem = ChartItem(label: transaction.category, value: 0);
            scopedCategoriesNegativeTotals.add(newChartItem);
            return newChartItem;
          }
        );
        chartItem.value += transaction.value;

        scopedMonthlyNegativeTotals[transaction.date.month] = transaction.value + (scopedMonthlyPostitiveTotals[transaction.date.month] ?? 0);
        categoryMonthTotal.negatives[transaction.category] = transaction.value.abs() + (categoryMonthTotal.negatives[transaction.category] ?? 0);
      }
    }

    List<ChartItem> scopedCategoriesPositiveTotalsPercents = [];
    List<ChartItem> scopedCategoriesNegativeTotalsPercents = [];
    List<ChartItem> scopedSimplifiedCategoriesPositiveTotalsPercents = [];
    List<ChartItem> scopedSimplifiedCategoriesNegativeTotalsPercents = [];
    if (scopedCategoriesPositiveTotals.isNotEmpty) {
      double catergoriesTotal = scopedCategoriesPositiveTotals.map((item) => item.value).reduce((value, element) => value + element);
      scopedCategoriesPositiveTotalsPercents = scopedCategoriesPositiveTotals.map((item) => ChartItem(label: item.label, value: item.value / catergoriesTotal * 100)).toList();

      double otherPercentTotal = 0;
      for (var item in scopedCategoriesPositiveTotalsPercents) {
        if (item.value > 1) {
          scopedSimplifiedCategoriesPositiveTotalsPercents.add(ChartItem(label: item.label, value: item.value));
        } else {
          otherPercentTotal += item.value;
        }
      }
      scopedSimplifiedCategoriesPositiveTotalsPercents.add(ChartItem(label: 'Autre', value: otherPercentTotal));
    }

    if (scopedCategoriesNegativeTotals.isNotEmpty) {
      double catergoriesTotal = scopedCategoriesNegativeTotals.map((item) => item.value).reduce((value, element) => value + element);
      scopedCategoriesNegativeTotalsPercents = scopedCategoriesNegativeTotals.map((item) => ChartItem(label: item.label, value: item.value / catergoriesTotal * 100)).toList();

      double otherPercentTotal = 0;
      for (var item in scopedCategoriesNegativeTotalsPercents) {
        if (item.value > 1) {
          scopedSimplifiedCategoriesNegativeTotalsPercents.add(ChartItem(label: item.label, value: item.value));
        } else {
          otherPercentTotal += item.value;
        }
      }
      scopedSimplifiedCategoriesNegativeTotalsPercents.add(ChartItem(label: 'Autre', value: otherPercentTotal));
    }

    List<ChartItem> scopedSimplifiedCategoriesPositiveTotals = [];
    List<ChartItem> scopedSimplifiedCategoriesNegativeTotals = [];

    scopedCategoriesPositiveTotals.sort((a, b) => b.value.compareTo(a.value));
    scopedCategoriesPositiveTotalsPercents.sort((a, b) => b.value.compareTo(a.value));
    scopedCategoriesNegativeTotals.sort((a, b) => a.value.compareTo(b.value));
    scopedCategoriesNegativeTotalsPercents.sort((a, b) => a.value.compareTo(b.value));
    scopedSimplifiedCategoriesPositiveTotals.sort((a, b) => b.value.compareTo(a.value));
    scopedSimplifiedCategoriesPositiveTotalsPercents.sort((a, b) => b.value.compareTo(a.value));
    scopedSimplifiedCategoriesNegativeTotals.sort((a, b) => a.value.compareTo(b.value));
    scopedSimplifiedCategoriesNegativeTotalsPercents.sort((a, b) => a.value.compareTo(b.value));

    for (var monthTotals in scopedCategoriesMonthlyTotals.values) {
      _sortMapByValues(monthTotals.positives);
      _sortMapByValues(monthTotals.negatives);
    }

    List<FlSpot> scopedMonthlyTotals = scopedMonthlyTotalsMap.values.toList();
    scopedMonthlyTotals.sort((a, b) => a.x.compareTo(b.x));

    return state.copyWith(
      scoppedProfit: scoppedTotal,
      scopedCategoriesPositiveTotals: scopedCategoriesPositiveTotals,
      scopedCategoriesPositiveTotalsPercents: scopedCategoriesPositiveTotalsPercents,
      scopedCategoriesNegativeTotals: scopedCategoriesNegativeTotals,
      scopedCategoriesNegativeTotalsPercents: scopedCategoriesNegativeTotalsPercents,
      scopedSimplifiedCategoriesPositiveTotals: scopedSimplifiedCategoriesPositiveTotals,
      scopedSimplifiedCategoriesPositiveTotalsPercents: scopedSimplifiedCategoriesPositiveTotalsPercents,
      scopedSimplifiedCategoriesNegativeTotals: scopedSimplifiedCategoriesNegativeTotals,
      scopedSimplifiedCategoriesNegativeTotalsPercents: scopedSimplifiedCategoriesNegativeTotalsPercents,
      scopedMonthlyTotals: scopedMonthlyTotals,
      scopedCategoriesMonthlyTotals: scopedCategoriesMonthlyTotals,
      scopedMonthlyPostitiveTotals: scopedMonthlyPostitiveTotals,
      scopedMonthlyNegativeTotals: scopedMonthlyNegativeTotals,
    );
  }

  Map<dynamic, dynamic> _sortMapByValues(Map<dynamic, dynamic> map) {
    final sortedEntries = map.entries.toList()..sort((a, b) {
      var diff = b.value.compareTo(a.value);
      return diff;
    });

    return map
      ..clear()
      ..addEntries(sortedEntries);
  }
}
