import 'package:flutter/material.dart';

import 'package:pshared/controllers/payment/source.dart';
import 'package:pshared/models/payment/source_type.dart';
import 'package:pshared/models/payment/wallet.dart';

import 'package:pweb/widgets/payment/source_wallet_selector/options.dart';
import 'package:pweb/widgets/payment/source_wallet_selector/selector_field.dart';


class SourceWalletSelector extends StatelessWidget {
  const SourceWalletSelector({
    super.key,
    required this.sourceController,
    this.isBusy = false,
    this.onChanged,
  });

  final PaymentSourceController sourceController;
  final bool isBusy;
  final ValueChanged<Wallet>? onChanged;

  @override
  Widget build(BuildContext context) {
    final source = sourceController;

    return buildSourceSelectorField(
      context: context,
      wallets: source.wallets,
      ledgerAccounts: source.ledgerAccounts,
      selectedValue: resolveSelectedSourceOption(source),
      onChanged: (value) => _onSourceChanged(source, value),
      isBusy: isBusy,
    );
  }

  void _onSourceChanged(PaymentSourceController source, SourceOptionKey value) {
    if (value.type == PaymentSourceType.wallet) {
      source.selectWalletByRef(value.ref);
      final selected = source.selectedWallet;
      if (selected != null) {
        onChanged?.call(selected);
      }
      return;
    }

    if (value.type == PaymentSourceType.ledger) {
      source.selectLedgerByRef(value.ref);
    }
  }
}
