import 'package:flutter/material.dart';

import 'package:pweb/models/payment/source_funds.dart';
import 'package:pweb/pages/payout_page/send/widgets/section/card.dart';
import 'package:pweb/pages/payout_page/send/widgets/section/title.dart';


class SourceOfFundsPanel extends StatelessWidget {
  const SourceOfFundsPanel({
    super.key,
    required this.title,
    required this.sourceSelector,
    this.visibleStates = const <SourceOfFundsVisibleState>{},
    this.stateWidgets = const <SourceOfFundsVisibleState, Widget>{},
    this.selectorSpacing = 8,
    this.sectionSpacing = 12,
    this.padding,
  });

  final String title;
  final Widget sourceSelector;
  final Set<SourceOfFundsVisibleState> visibleStates;
  final Map<SourceOfFundsVisibleState, Widget> stateWidgets;
  final double selectorSpacing;
  final double sectionSpacing;
  final EdgeInsetsGeometry? padding;

  @override
  Widget build(BuildContext context) {
    final headerAction = _stateWidget(SourceOfFundsVisibleState.headerAction);
    final headerActions = headerAction == null
        ? const <Widget>[]
        : <Widget>[headerAction];
    final bodySections = _buildBodySections();

    return PaymentSectionCard(
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(child: SectionTitle(title)),
              ...headerActions,
            ],
          ),
          SizedBox(height: selectorSpacing),
          sourceSelector,
          if (bodySections.isNotEmpty) ...[
            SizedBox(height: sectionSpacing),
            const Divider(height: 1),
            SizedBox(height: sectionSpacing),
            ...bodySections,
          ],
        ],
      ),
    );
  }

  List<Widget> _buildBodySections() {
    const orderedStates = <SourceOfFundsVisibleState>[
      SourceOfFundsVisibleState.summary,
      SourceOfFundsVisibleState.quoteStatus,
      SourceOfFundsVisibleState.sendAction,
    ];

    final sections = <Widget>[];
    for (final state in orderedStates) {
      final section = _stateWidget(state);
      if (section == null) continue;
      if (sections.isNotEmpty) {
        sections.add(SizedBox(height: sectionSpacing));
      }
      sections.add(section);
    }
    return sections;
  }

  Widget? _stateWidget(SourceOfFundsVisibleState state) {
    if (!visibleStates.contains(state)) return null;
    return stateWidgets[state];
  }
}
