import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/controllers/balance_mask/wallets.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:pweb/pages/payment_methods/payment_page/body.dart';
import 'package:pweb/utils/recipient/filtering.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;
  Recipient? _previousRecipient;
  String _query = '';

  @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) {
    setState(() {
      _query = query;
    });
  }

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

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

  void _clearSearchField() {
    _searchController.clear();
    _searchFocusNode.unfocus();
    setState(() {
      _query = '';
    });
  }

  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.watch<RecipientsProvider>();
    final recipient = recipientProvider.currentObject;
    final filteredRecipients = filterRecipients(
      recipients: recipientProvider.recipients,
      query: _query,
    );

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