import 'package:flutter/material.dart';

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

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

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

class _AccountListState extends State<AccountList> {
  final AccountController _accountController = AccountController();
  List<Account> _accounts = [];

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

    _accounts = _accountController.accounts.value;

    _accountController.accounts.addListener(() {
      if (mounted) {
        setState(() {
          if (mounted) {
            _accounts = _accountController.accounts.value;
          }
        });
      }
    });
  }

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

      return EditableList(
        name: 'Konten',
        items: formatedAccounts,
        onAdd: _accountController.newAccountHandler,
        onEdit: _accountController.renameAccountHandler,
        onDelete: _accountController.deleteAccountHandler,
        icon: const Icon(Icons.account_balance_wallet),
        addTooltip: 'Konto hinzufügen',
        menuTooltip: 'Menü anzeigen',
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  }
}
