import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/controllers/balance_mask/wallets.dart';
import 'package:pshared/provider/ledger.dart';
import 'package:pshared/models/payment/wallet.dart';

import 'package:pweb/pages/dashboard/buttons/balance/carousel.dart';
import 'package:pweb/pages/dashboard/buttons/balance/controller.dart';
import 'package:pweb/pages/dashboard/buttons/balance/balance_item.dart';

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


class BalanceWidget extends StatelessWidget {
  final ValueChanged<Wallet> onTopUp;
  final ValueChanged<Wallet> onWalletTap;

  const BalanceWidget({
    super.key,
    required this.onTopUp,
    required this.onWalletTap,
  });

  @override
  Widget build(BuildContext context) {
    final walletsController = context.watch<WalletsController>();
    final ledgerProvider = context.watch<LedgerAccountsProvider>();
    final carousel = context.watch<CarouselIndexController>();
    final loc = AppLocalizations.of(context)!;

    final wallets = walletsController.wallets;
    final accounts = ledgerProvider.accounts;
    final isLoading = walletsController.isLoading &&
        ledgerProvider.isLoading &&
        wallets.isEmpty &&
        accounts.isEmpty;

    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    final items = [
      ...wallets.map(BalanceItem.wallet),
      ...accounts.map(BalanceItem.ledger),
      const BalanceItem.addAction(),
    ];

    if (items.isEmpty) {
      return const SizedBox.shrink();
    }

    // Ensure index is always valid when list changes
    carousel.setIndex(carousel.index, items.length);

    final index = carousel.index;
    final current = items[index];

    // Single source of truth: controller
    if (current.isWallet) {
      final wallet = current.wallet!;
      if (walletsController.selectedWallet?.id != wallet.id) {
        walletsController.selectWallet(wallet);
      }
    }

    final carouselWidget = BalanceCarousel(
      items: items,
      currentIndex: index,
      onIndexChanged: (i) {
        carousel.setIndex(i, items.length);
        final next = items[carousel.index];
        if (next.isWallet) {
          walletsController.selectWallet(next.wallet!);
        }
      },
      onTopUp: onTopUp,
      onWalletTap: onWalletTap,
    );

    if (wallets.isEmpty && accounts.isEmpty) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Center(child: Text(loc.noWalletsAvailable)),
          const SizedBox(height: 12),
          carouselWidget,
        ],
      );
    }

    return carouselWidget;
  }
}
