import 'package:flutter/foundation.dart';

import 'package:pshared/models/payment/type.dart';

import 'package:pweb/controllers/organization/address_book_recipient_form.dart';


class AddressBookRecipientFormSelectionController extends ChangeNotifier {
  AddressBookRecipientFormController? _formController;
  PaymentType? _selectedType;
  int? _selectedIndex;

  PaymentType? get selectedType => _selectedType;
  int? get selectedIndex => _selectedIndex;

  void update(AddressBookRecipientFormController formController) {
    if (identical(_formController, formController)) return;
    _formController?.removeListener(_handleFormChanged);
    _formController = formController;
    _formController?.addListener(_handleFormChanged);
    _reconcileSelection();
  }

  void select(PaymentType type, int index) {
    if (_selectedType == type && _selectedIndex == index) return;
    _selectedType = type;
    _selectedIndex = index;
    notifyListeners();
  }

  void selectAfterAdd(PaymentType type, int? index) {
    if (_selectedType == type && _selectedIndex == index) return;
    _selectedType = type;
    _selectedIndex = index;
    notifyListeners();
  }

  void _handleFormChanged() {
    _reconcileSelection();
  }

  void _reconcileSelection() {
    final form = _formController;
    if (form == null) return;
    final types = form.supportedTypes;
    if (types.isEmpty) return;

    var nextType = _selectedType;
    var nextIndex = _selectedIndex;

    if (nextType == null || !types.contains(nextType)) {
      nextType = form.preferredType ?? types.first;
      nextIndex = null;
    }

    final entries = form.methods[nextType] ?? const [];
    if (entries.isEmpty) {
      nextIndex = null;
    } else if (nextIndex == null || nextIndex < 0 || nextIndex >= entries.length) {
      nextIndex = 0;
    }

    if (nextType == _selectedType && nextIndex == _selectedIndex) return;
    _selectedType = nextType;
    _selectedIndex = nextIndex;
    notifyListeners();
  }

  @override
  void dispose() {
    _formController?.removeListener(_handleFormChanged);
    super.dispose();
  }
}
