import 'package:flutter/foundation.dart';

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

import 'package:pweb/providers/page_selector.dart';


class PaymentFlowProvider extends ChangeNotifier {
  PaymentType _selectedType;
  Object? _manualPaymentData;

  PaymentFlowProvider({
    required PaymentType initialType,
  }) : _selectedType = initialType;

  PaymentType get selectedType => _selectedType;
  Object? get manualPaymentData => _manualPaymentData;

  void syncWithSelector(PageSelectorProvider selector) {
    final recipient = selector.selectedRecipient;
    final resolvedType = _resolveSelectedType(selector, recipient);

    var hasChanges = false;
    if (resolvedType != _selectedType) {
      _selectedType = resolvedType;
      hasChanges = true;
    }

    if (recipient != null && _manualPaymentData != null) {
      _manualPaymentData = null;
      hasChanges = true;
    }

    if (hasChanges) notifyListeners();
  }

  void reset(PageSelectorProvider selector) {
    _selectedType = selector.getDefaultPaymentType();
    _manualPaymentData = null;
    notifyListeners();
  }

  void selectType(PaymentType type, {bool resetManualData = false}) {
    if (_selectedType == type && (!resetManualData || _manualPaymentData == null)) {
      return;
    }

    _selectedType = type;
    if (resetManualData) {
      _manualPaymentData = null;
    }
    notifyListeners();
  }

  void setManualPaymentData(Object? data) {
    _manualPaymentData = data;
    notifyListeners();
  }

  PaymentType _resolveSelectedType(
    PageSelectorProvider selector,
    Recipient? recipient,
  ) {
    final available = selector.getAvailablePaymentTypes();
    final current = _selectedType;

    if (recipient == null) {
      return current;
    }

    if (available.keys.contains(current)) {
      return current;
    }

    return selector.getDefaultPaymentType();
  }
}
