import 'package:flutter/material.dart';

import '../../Controller/recurring_transaction_controller.dart';
import '../../Entities/drift_database.dart';
import '../../Entities/list_item.dart';
import '../Misc/editable_list.dart';

/// Ein Widget,
/// das die Liste mit vorhandenen wiederkehrenden Transaktionen anzeigt
class RecurringTransactionList extends StatefulWidget {
  /// Erstellt eine neue Instanz dieser Klasse
  const RecurringTransactionList({super.key});

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

class _RecurringTransactionListState extends State<RecurringTransactionList> {
  final RecurringTransactionController _recurringTransactionController =
      RecurringTransactionController();
  List<RecurringTransaction> _recurringTransactions = [];

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

    _recurringTransactions =
        _recurringTransactionController.recurringTransactions.value;

    _recurringTransactionController.recurringTransactions.addListener(() {
      if (mounted) {
        setState(() {
          if (mounted) {
            _recurringTransactions =
                _recurringTransactionController.recurringTransactions.value;
          }
        });
      }
    });
  }

  @override
  Widget build(final BuildContext context) {
    if (_recurringTransactions != []) {
      final List<ListItem> formatedRecurringTransactions = [];
      for (final RecurringTransaction data in _recurringTransactions) {
        formatedRecurringTransactions.add(
          ListItem(id: data.id, name: data.name),
        );
      }

      return EditableList(
        name: 'Wiederkehrende Transaktionen',
        items: formatedRecurringTransactions,
        onAdd: _recurringTransactionController.newRecurringTransactionHandler,
        onEdit: _recurringTransactionController.editRecurringTransactionHandler,
        onDelete:
            _recurringTransactionController.deleteRecurringTransactionHandler,
        icon: const Icon(Icons.repeat),
        addTooltip: 'Wiederkehrende Transaktion hinzufügen',
        menuTooltip: 'Menü anzeigen',
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  }
}
