import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

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

import 'package:pweb/widgets/sidebar/destinations.dart';
import 'package:pweb/controllers/payments/page_ui.dart';
import 'package:pweb/utils/payment/page_handlers.dart';
import 'package:pweb/pages/payout_page/send/page_view.dart';


class PaymentPage extends StatefulWidget {
  final ValueChanged<Recipient?>? onBack;
  final PaymentType? initialPaymentType;
  final String? initialDestinationLedgerAccountRef;
  final PayoutDestination fallbackDestination;

  const PaymentPage({
    super.key,
    this.onBack,
    this.initialPaymentType,
    this.initialDestinationLedgerAccountRef,
    this.fallbackDestination = PayoutDestination.dashboard,
  });

  @override
  State<PaymentPage> createState() => _PaymentPageState();
}

class _PaymentPageState extends State<PaymentPage> {
  late final PaymentPageUiController _uiController;

  @override
  void initState() {
    super.initState();
    _uiController = PaymentPageUiController();

    WidgetsBinding.instance.addPostFrameCallback(
      (_) => initializePaymentPage(
        context,
        widget.initialPaymentType,
        destinationLedgerAccountRef: widget.initialDestinationLedgerAccountRef,
      ),
    );
  }

  @override
  void dispose() {
    context.read<PaymentAmountProvider>().setComment('');
    _uiController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PaymentPageView(
      uiController: _uiController,
      onBack: widget.onBack,
      fallbackDestination: widget.fallbackDestination,
      onSearchChanged: (query) => handleSearchChanged(_uiController, query),
      onRecipientSelected: (recipient) =>
          handleRecipientSelected(context, _uiController, recipient),
      onRecipientCleared: () => handleRecipientCleared(context, _uiController),
      onSend: () => handleSendPayment(
        state: this,
        fallbackDestination: widget.fallbackDestination,
      ),
      onAddRecipient: () => handleAddRecipient(context),
      onAddPaymentMethod: () => handleAddPaymentMethod(context),
    );
  }
}
