import 'package:flutter/material.dart';

import 'package:pshared/models/payment/type.dart';
import 'package:pshared/models/recipient/payment_method_draft.dart';

import 'package:pweb/models/payment/method_tile/availability.dart';
import 'package:pweb/models/payment/method_tile/selection.dart';
import 'package:pweb/pages/address_book/form/widgets/payment_methods/add_button.dart';
import 'package:pweb/pages/address_book/form/widgets/payment_methods/tile.dart';


class PaymentMethodSelectorRow extends StatelessWidget {
  final List<PaymentType> types;
  final PaymentType selectedType;
  final int? selectedIndex;
  final Map<PaymentType, List<RecipientMethodDraft>> methods;
  final void Function(PaymentType type, int index) onSelected;
  final ValueChanged<PaymentType>? onAdd;
  final VoidCallback? onAddPressed;
  final Set<PaymentType> disabledTypes;
  final String? Function(RecipientMethodDraft entry)? detailsBuilder;

  final double spacing;
  final double tilePadding;
  final double runSpacing;

  const PaymentMethodSelectorRow({
    super.key,
    required this.types,
    required this.selectedType,
    required this.selectedIndex,
    required this.methods,
    required this.onSelected,
    this.onAdd,
    this.onAddPressed,
    this.disabledTypes = const {},
    this.detailsBuilder,
    this.spacing = 12,
    this.tilePadding = 10,
    this.runSpacing = 12,
  });

  @override
  Widget build(BuildContext context) {
    final tiles = <Widget>[];
    for (final type in types) {
      final entries = methods[type] ?? const <RecipientMethodDraft>[];
      for (var index = 0; index < entries.length; index += 1) {
        final entry = entries[index];
        final isSelected = type == selectedType && selectedIndex == index;
        final selection = isSelected
            ? PaymentMethodTileSelection.selected
            : PaymentMethodTileSelection.idle;
        final isAdded = entry.data != null || entry.existing != null;
        final availability = isAdded
            ? PaymentMethodTileAvailability.added
            : PaymentMethodTileAvailability.available;
        final detailsText = detailsBuilder?.call(entry);
        tiles.add(
          PaymentMethodTile(
            type: type,
            selection: selection,
            availability: availability,
            padding: tilePadding,
            detailsText: detailsText,
            onTap: () => onSelected(type, index),
          ),
        );
      }
    }

    tiles.add(
      AddPaymentMethodButton(
        types: types,
        disabledTypes: disabledTypes,
        onAdd: onAdd,
        onPressed: onAddPressed,
      ),
    );

    return Wrap(
      spacing: spacing,
      runSpacing: runSpacing,
      alignment: WrapAlignment.start,
      children: tiles,
    );
  }
}
