import 'dart:async';

import 'package:flutter/material.dart';

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

/// Eine Liste mit den zuletzt getätigten Transaktionen
class RecentTransactionsList extends StatefulWidget {
  /// Erstellt eine neue Instanz dieser Klasse
  const RecentTransactionsList({super.key});

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

class _RecentTransactionsListState extends State<RecentTransactionsList> {
  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) {
    final Future<List<Transaction>> recentTransactions = _transactionRepository
        .findBy(
          account: _accountController.selected.value,
          dateTo: DateTime.now(),
          limit: 5,
          orderBy: 'dateDesc',
        );

    return FutureBuilder(
      future: recentTransactions,
      builder:
          (
            final BuildContext context,
            final AsyncSnapshot<List<Transaction>> snapshot,
          ) {
            final ThemeData theme = Theme.of(context);

            if (snapshot.hasData) {
              final List<Widget>? recentTransactionsWidgetList = snapshot.data
                  ?.map(
                    (final Transaction transaction) => Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4),
                      child: ListTile(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        onTap: () {
                          unawaited(
                            _transactionController.editTransactionHandler(
                              transaction.id,
                            ),
                          );
                        },
                        title: Text(
                          transaction.name,
                          style: (transaction.checked)
                              ? const TextStyle()
                              : TextStyle(color: theme.colorScheme.error),
                        ),
                        trailing: Text(
                          '${transaction.amount.abs().toStringAsFixed(2)} €',
                          style: TextStyle(
                            color: transaction.amount == 0
                                ? null
                                : (transaction.amount < 0
                                      ? Colors.green
                                      : Colors.red),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  )
                  .toList();

              if (recentTransactionsWidgetList != null &&
                  recentTransactionsWidgetList.isNotEmpty) {
                recentTransactionsWidgetList.add(
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 4),
                    child: TextButton(
                      onPressed: _transactionController.newTransactionHandler,
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.swap_horiz),
                          SizedBox(width: 10),
                          Text('Transaktion hinzufügen'),
                        ],
                      ),
                    ),
                  ),
                );
                return Column(children: [...recentTransactionsWidgetList]);
              } else {
                if (_accountController.selected.value != null) {
                  return TextButton(
                    onPressed: _transactionController.newTransactionHandler,
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.swap_horiz),
                        SizedBox(width: 10),
                        Text('Transaktion hinzufügen'),
                      ],
                    ),
                  );
                } else {
                  return const Text('');
                }
              }
            } else if (snapshot.hasError) {
              return Center(
                child: Column(
                  children: [
                    Icon(Icons.error, color: theme.colorScheme.error),
                    const Text('Fehler beim holen der letzten Transaktionen!'),
                  ],
                ),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
    );
  }
}
