import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/domains/budget/budget_bloc.dart';
import 'package:krezus/repositories/metadata/models/budget.dart';

class BudgetRadar extends StatelessWidget {
  const BudgetRadar({super.key});

  List<RadarDataSet> _computeDataSet(BuildContext context, List<Budget> targetBudgets, List<Budget> realBudgets) {
    if (realBudgets.isEmpty || targetBudgets.isEmpty) {
      return [RadarDataSet(dataEntries: [const RadarEntry(value: 1), const RadarEntry(value: 2), const RadarEntry(value: 3)])];
    }

    RadarDataSet targetDataSet = RadarDataSet(
      fillColor: Theme.of(context).colorScheme.primary.withAlpha(100),
      borderColor: Theme.of(context).colorScheme.primary,
      entryRadius: 5,
      dataEntries: targetBudgets.map((budget) => RadarEntry(value: budget.value)).toList(),
    );

    if (realBudgets.isNotEmpty) {
      targetDataSet.dataEntries.add(const RadarEntry(value: 0));
    }

    RadarDataSet realDataSet = RadarDataSet(
      fillColor: Theme.of(context).colorScheme.onPrimary.withAlpha(100),
      borderColor: Theme.of(context).colorScheme.onPrimary,
      entryRadius: 8,
      dataEntries: realBudgets.map((budget) => RadarEntry(value: budget.value)).toList(),
    );

    return [realDataSet, targetDataSet];
  }

  RadarChartTitle _computeDataSetTitle(int index, List<Budget> realBudgets) {
    return RadarChartTitle(text: realBudgets[index].label);
  }

  bool canShowData(List<Budget> targetBudgets, List<Budget> realBudgets) {
    return realBudgets.length >= 3 && targetBudgets.length >= 3;
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BudgetBloc, BudgetState>(
      builder: (context, state) => canShowData(state.budgets, state.compareBudgets) ? Expanded(
        child: AspectRatio(
          aspectRatio: 1.3,
          child: RadarChart(
            RadarChartData(
              titlePositionPercentageOffset: 0.15,
              tickBorderData: BorderSide(color: Theme.of(context).colorScheme.secondary, width: 1),
              gridBorderData: BorderSide(color: Theme.of(context).colorScheme.secondary, width: 2),
              radarBorderData: BorderSide(color: Theme.of(context).colorScheme.secondary, width: 3),
              radarBackgroundColor: Theme.of(context).colorScheme.secondaryContainer.withAlpha(100),
              radarShape: RadarShape.circle,
              dataSets: _computeDataSet(context, state.budgets, state.compareBudgets),
              getTitle: (index, angle) => _computeDataSetTitle(index, state.compareBudgets),
            )
          ),
        )
      )
      : const Text('No data to show'),
    );
  }
}