import 'package:pshared/models/payment/type.dart';
import 'package:pshared/models/recipient/payment_method_draft.dart';
import 'package:pshared/provider/payment/flow.dart';


class PaymentInfoMethodsState {
  final List<PaymentType> types;
  final Map<PaymentType, List<RecipientMethodDraft>> methodsMap;
  final PaymentType selectedType;
  final List<RecipientMethodDraft> selectedEntries;
  final int? selectedIndex;

  const PaymentInfoMethodsState({
    required this.types,
    required this.methodsMap,
    required this.selectedType,
    required this.selectedEntries,
    required this.selectedIndex,
  });

  bool get hasSelection => selectedIndex != null && selectedIndex! >= 0;
}

PaymentInfoMethodsState buildPaymentInfoMethodsState({
  required PaymentFlowProvider flowProvider,
  required List<PaymentType> types,
}) {
  final methods = flowProvider.methodsForRecipient;
  final selectedMethod = flowProvider.selectedMethod;
  final methodsMap = <PaymentType, List<RecipientMethodDraft>>{};
  for (final method in methods) {
    methodsMap.putIfAbsent(method.type, () => []).add(
          RecipientMethodDraft(
            type: method.type,
            existing: method,
          ),
        );
  }

  final fallbackType = methods.isNotEmpty
      ? methods.first.type
      : (types.isNotEmpty ? types.first : PaymentType.bankAccount);
  final selectedType = selectedMethod?.type ?? fallbackType;
  final selectedEntries =
      methodsMap[selectedType] ?? const <RecipientMethodDraft>[];
  final selectedIndex = selectedMethod == null
      ? null
      : selectedEntries.indexWhere(
          (entry) => entry.existing?.id == selectedMethod.id,
        );

  return PaymentInfoMethodsState(
    types: types,
    methodsMap: methodsMap,
    selectedType: selectedType,
    selectedEntries: selectedEntries,
    selectedIndex: selectedIndex,
  );
}
