import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/payment/wallets.dart';

import 'package:pweb/models/visibility.dart';

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


class WalletBalanceRefreshButton extends StatelessWidget {
  final String walletId;
  final VisibilityState iconOnly;
  final double iconSize = 18;

  const WalletBalanceRefreshButton({
    super.key,
    required this.walletId,
    this.iconOnly = VisibilityState.visible,
  });

  @override
  Widget build(BuildContext context) {
    final walletsProvider = context.watch<WalletsProvider>();
    final loc = AppLocalizations.of(context)!;
    final isBusy = walletsProvider.isWalletRefreshing(walletId) || walletsProvider.isLoading;
    final hasTarget = walletsProvider.wallets.any((w) => w.id == walletId);

    void refresh() {
      final provider = context.read<WalletsProvider>();
      provider.refreshBalance(walletId);
    }

    if (iconOnly == VisibilityState.hidden) {
      return IconButton(
        tooltip: loc.refreshBalance,
        onPressed: hasTarget && !isBusy ? refresh : null,
        icon: isBusy
            ? SizedBox(
                width: iconSize,
                height: iconSize,
                child: const CircularProgressIndicator(strokeWidth: 2),
              )
            : const Icon(Icons.refresh),
      );
    }

    return TextButton.icon(
      onPressed: hasTarget && !isBusy ? refresh : null,
      icon: isBusy
          ? SizedBox(
              width: iconSize,
              height: iconSize,
              child: const CircularProgressIndicator(strokeWidth: 2),
            )
          : const Icon(Icons.refresh),
      label: Text(loc.refreshBalance),
      style: TextButton.styleFrom(visualDensity: VisualDensity.compact),
    );
  }
}
