import 'package:flutter/widgets.dart';

import 'package:pshared/models/payment/methods/card_token.dart';
import 'package:pshared/models/payment/methods/ledger.dart';
import 'package:pshared/models/payment/methods/managed_wallet.dart';
import 'package:pshared/models/payment/methods/type.dart';
import 'package:pshared/models/payment/type.dart';

import 'package:pweb/utils/payment/masking.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


String getPaymentTypeLabel(BuildContext context, PaymentType type) {
  final l10n = AppLocalizations.of(context)!;
  return switch (type) {
    PaymentType.card => l10n.paymentTypeCard,
    PaymentType.cardToken => l10n.paymentTypeCardToken,
    PaymentType.bankAccount => l10n.paymentTypeBankAccount,
    PaymentType.iban => l10n.paymentTypeIban,
    PaymentType.wallet => l10n.paymentTypeWallet,
    PaymentType.managedWallet => l10n.paymentTypeManagedWallet,
    PaymentType.externalChain => l10n.paymentTypeCryptoAddress,
    PaymentType.ledger => l10n.paymentTypeLedger,
  };
}

String? getPaymentMethodMaskedValue(PaymentMethod m) => switch (m.type) {
  PaymentType.card => maskCardNumber(m.cardData?.pan),
  PaymentType.cardToken => m.dataAsOrNull<CardTokenPaymentMethod>()?.maskedPan,
  PaymentType.bankAccount => maskAccountEdge(m.bankAccountData?.accountNumber),
  PaymentType.iban => maskAccountEdge(m.ibanData?.iban),
  PaymentType.wallet => maskAccountEdge(m.walletData?.walletId),
  PaymentType.managedWallet => () {
    final data = m.dataAsOrNull<ManagedWalletPaymentMethod>();
    if (data == null) return null;
    return data.asset?.tokenSymbol ?? maskAccountEdge(data.managedWalletRef);
  }(),
  PaymentType.externalChain => maskAccountEdge(m.cryptoAddressData?.address),
  PaymentType.ledger => maskAccountEdge(m.dataAsOrNull<LedgerPaymentMethod>()?.ledgerAccountRef),
};

String getPaymentTypeDescription(BuildContext context, PaymentMethod m) {
  return getPaymentMethodMaskedValue(m) ?? AppLocalizations.of(context)!.notSet;
}

String? getPaymentMethodAccountId(PaymentMethod m) => _accountIdentifier(m);

String? _accountIdentifier(PaymentMethod m) => switch (m.type) {
  PaymentType.card => m.cardData?.pan,
  PaymentType.cardToken => m.dataAsOrNull<CardTokenPaymentMethod>()?.maskedPan,
  PaymentType.bankAccount => m.bankAccountData?.accountNumber,
  PaymentType.iban => m.ibanData?.iban,
  PaymentType.wallet => m.walletData?.walletId,
  PaymentType.managedWallet => m.dataAsOrNull<ManagedWalletPaymentMethod>()?.managedWalletRef,
  PaymentType.externalChain => m.cryptoAddressData?.address,
  PaymentType.ledger => m.dataAsOrNull<LedgerPaymentMethod>()?.ledgerAccountRef,
};
