import 'package:flutter/material.dart';

import '../../Controller/account_controller.dart';
import '../../Controller/transaction_controller.dart';
import '../../Repositories/transaction_repository.dart';

/// Gibt eine Übersicht über den aktuellen Kontostand
/// und der Veränderung zum Vormonat zurück
class CurrentBalance extends StatefulWidget {
  /// Erstellt eine neue Instanz dieser Klasse
  const CurrentBalance({super.key});

  @override
  State<StatefulWidget> createState() => _CurrentBalanceState();
}

class _CurrentBalanceState extends State<CurrentBalance> {
  final TransactionController _transactionController = TransactionController();
  final AccountController _accountController = AccountController();

  final TransactionRepository _transactionRepository = TransactionRepository();

  @override
  void initState() {
    super.initState();

    _transactionController.transactions.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(final BuildContext context) => FutureBuilder(
    future: _getBalance(),
    builder:
        (
          final BuildContext context,
          final AsyncSnapshot<(double, double, double)> snapshot,
        ) {
          final ThemeData theme = Theme.of(context);

          Widget widget;

          if (snapshot.hasData) {
            final double balanceOfLastMonth = snapshot.data!.$1;
            final double balanceNow = snapshot.data!.$2;
            final double balanceOfThisMonth = snapshot.data!.$3;

            final double diff = balanceOfThisMonth - balanceOfLastMonth;

            widget = Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text('Aktuell', style: theme.textTheme.bodyMedium),
                    const SizedBox(height: 8),
                    Text(
                      '${balanceNow.toStringAsFixed(2)} €',
                      style: theme.textTheme.headlineSmall?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),

                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      'Differenz zum Vormonat',
                      style: theme.textTheme.bodySmall?.copyWith(
                        color: theme.colorScheme.onSurface,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: <Widget>[
                        Icon(
                          diff >= 0 ? Icons.arrow_upward : Icons.arrow_downward,
                          color: diff >= 0 ? Colors.green : Colors.red,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${diff.abs().toStringAsFixed(2)} €',
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                            color: diff >= 0 ? Colors.green : Colors.red,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            );
          } else if (snapshot.hasError) {
            widget = Column(
              children: [
                Icon(Icons.error, color: theme.colorScheme.error),
                const Text('Fehler beim holen der letzten Transaktionen!'),
              ],
            );
          } else {
            widget = const Center(child: CircularProgressIndicator());
          }

          return Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: theme.colorScheme.primaryContainer,
              borderRadius: BorderRadius.circular(16),
            ),
            child: widget,
          );
        },
  );

  Future<(double, double, double)> _getBalance() async {
    final now = DateTime.now();
    final dateOfLastMonth = DateTime(now.year, now.month, 0);
    final dateOfThisMonth = DateTime(now.year, now.month + 1, 0);

    final double balanceOfLastMonth = await _transactionRepository.balance(
      account: _accountController.selected.value,
      until: dateOfLastMonth,
    );
    final double balanceNow = await _transactionRepository.balance(
      account: _accountController.selected.value,
      until: now,
    );
    final double balanceOfThisMonth = await _transactionRepository.balance(
      account: _accountController.selected.value,
      until: dateOfThisMonth,
    );

    return (balanceOfLastMonth, balanceNow, balanceOfThisMonth);
  }
}
