import 'package:flutter/material.dart';

import 'package:pshared/models/ledger/account.dart';
import 'package:pshared/models/payment/wallet.dart';

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

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


Widget buildSourceSelectorField({
  required BuildContext context,
  required List<Wallet> wallets,
  required List<LedgerAccount> ledgerAccounts,
  required SourceOptionKey? selectedValue,
  required ValueChanged<SourceOptionKey> onChanged,
  required bool isBusy,
}) {
  final theme = Theme.of(context);
  final l10n = AppLocalizations.of(context)!;

  if (wallets.isEmpty && ledgerAccounts.isEmpty) {
    return Text(l10n.noWalletsAvailable, style: theme.textTheme.bodySmall);
  }

  final items = buildSourceSelectorItems(
    context: context,
    wallets: wallets,
    ledgerAccounts: ledgerAccounts,
    l10n: l10n,
  );

  final knownValues = items
      .map((item) => item.value)
      .whereType<SourceOptionKey>()
      .toSet();
  final effectiveValue = knownValues.contains(selectedValue)
      ? selectedValue
      : null;

  return DropdownButtonFormField<SourceOptionKey>(
    initialValue: effectiveValue,
    isExpanded: true,
    decoration: InputDecoration(
      labelText: l10n.whereGetMoney,
      border: const OutlineInputBorder(),
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
    ),
    items: items,
    onChanged: isBusy
        ? null
        : (value) {
            if (value == null) return;
            onChanged(value);
          },
  );
}
