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/flow.dart';
import 'package:pshared/provider/payment/provider.dart';
import 'package:pshared/provider/recipient/pmethods.dart';
import 'package:pshared/provider/recipient/provider.dart';
import 'package:pshared/provider/payment/wallets.dart';

import 'package:pweb/pages/payment_methods/payment_page/body.dart';
import 'package:pweb/widgets/sidebar/destinations.dart';
import 'package:pweb/services/posthog.dart';
import 'package:pweb/widgets/dialogs/payment_status_dialog.dart';


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

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

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

class _PaymentPageState extends State<PaymentPage> {
  late final TextEditingController _searchController;
  late final FocusNode _searchFocusNode;

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _searchFocusNode = FocusNode();

    WidgetsBinding.instance.addPostFrameCallback((_) => _initializePaymentPage());
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  void _initializePaymentPage() {
    final flowProvider = context.read<PaymentFlowProvider>();
    flowProvider.setPreferredType(widget.initialPaymentType);
  }

  void _handleSearchChanged(String query) {
    context.read<RecipientsProvider>().setQuery(query);
  }

  void _handleRecipientSelected(Recipient recipient) {
    final recipientProvider = context.read<RecipientsProvider>();
    recipientProvider.setCurrentObject(recipient.id);
    _clearSearchField();
  }

  void _handleRecipientCleared() {
    final recipientProvider = context.read<RecipientsProvider>();
    recipientProvider.setCurrentObject(null);
    _clearSearchField();
  }

  void _clearSearchField() {
    _searchController.clear();
    _searchFocusNode.unfocus();
    context.read<RecipientsProvider>().setQuery('');
  }

  void _handleSendPayment() {
    final flowProvider = context.read<PaymentFlowProvider>();
    final paymentProvider = context.read<PaymentProvider>();
    if (paymentProvider.isLoading) return;

    paymentProvider.pay().then((payment) {
      if (!mounted) return;
      final isSuccess = payment != null && paymentProvider.error == null;
      showPaymentStatusDialog(context, isSuccess: isSuccess);
      if (isSuccess) {
        PosthogService.paymentInitiated(method: flowProvider.selectedType);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final methodsProvider = context.watch<PaymentMethodsProvider>();
    final recipientProvider = context.read<RecipientsProvider>();
    final recipient = context.select<RecipientsProvider, Recipient?>(
      (provider) => provider.currentObject,
    );

    return PaymentPageBody(
      onBack: widget.onBack,
      fallbackDestination: widget.fallbackDestination,
      recipient: recipient,
      recipientProvider: recipientProvider,
      methodsProvider: methodsProvider,
      onWalletSelected: context.read<WalletsProvider>().selectWallet,
      searchController: _searchController,
      searchFocusNode: _searchFocusNode,
      onSearchChanged: _handleSearchChanged,
      onRecipientSelected: _handleRecipientSelected,
      onRecipientCleared: _handleRecipientCleared,
      onSend: _handleSendPayment,
    );
  }
}
