import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_swipe_button/flutter_swipe_button.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/data/models/transfer.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import '../../../l10n/app_localizations.dart';
import '../../fund_transfer/screens/transaction_pin_screen.dart';

class QuickPayWithinBankScreen extends StatefulWidget {
  final String debitAccount;
  const QuickPayWithinBankScreen({super.key, required this.debitAccount});

  @override
  State<QuickPayWithinBankScreen> createState() => _QuickPayWithinBankScreen();
}

class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController accountNumberController = TextEditingController();
  final TextEditingController confirmAccountNumberController =
      TextEditingController();
  final TextEditingController amountController = TextEditingController();
  String? _selectedAccountType;

  String? _beneficiaryName;
  bool _isValidating = false;
  bool _isBeneficiaryValidated = false;
  String? _validationError;

  @override
  void initState() {
    super.initState();
    accountNumberController.addListener(_resetBeneficiaryValidation);
    confirmAccountNumberController.addListener(_resetBeneficiaryValidation);
  }

  void _resetBeneficiaryValidation() {
    if (_isBeneficiaryValidated ||
        _beneficiaryName != null ||
        _validationError != null) {
      setState(() {
        _isBeneficiaryValidated = false;
        _beneficiaryName = null;
        _validationError = null;
      });
    }
  }

  @override
  void dispose() {
    accountNumberController.removeListener(_resetBeneficiaryValidation);
    confirmAccountNumberController.removeListener(_resetBeneficiaryValidation);
    accountNumberController.dispose();
    confirmAccountNumberController.dispose();
    amountController.dispose();
    super.dispose();
  }

  Future<void> _validateBeneficiary() async {
    var beneficiaryService = getIt<BeneficiaryService>();
    setState(() {
      _isValidating = true;
      _validationError = null;
    });
    try {
      final name = await beneficiaryService
          .validateBeneficiaryWithinBank(accountNumberController.text);
      setState(() {
        _beneficiaryName = name;
        _isBeneficiaryValidated = true;
        _isValidating = false;
      });
    } catch (e) {
      setState(() {
        _validationError = "Account Number not from KCCB";
        _isValidating = false;
        _isBeneficiaryValidated = false;
        _beneficiaryName = null;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          AppLocalizations.of(context).quickPayOwnBank,
          style: TextStyle(
              color: Theme.of(context).colorScheme.onSurface,
              fontWeight: FontWeight.w500),
        ),
        centerTitle: false,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              const SizedBox(height: 10),
              TextFormField(
                decoration: InputDecoration(
                  labelText: AppLocalizations.of(context).debitAccountNumber,
                  border: const OutlineInputBorder(),
                  isDense: true,
                  filled: true,
                  fillColor: Theme.of(context).scaffoldBackgroundColor,
                ),
                readOnly: true,
                controller: TextEditingController(text: widget.debitAccount),
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.next,
                enabled: false,
              ),
              const SizedBox(height: 20),
              TextFormField(
                decoration: InputDecoration(
                  labelText: AppLocalizations.of(context).accountNumber,
                  border: const OutlineInputBorder(),
                  isDense: true,
                  filled: true,
                  fillColor: Theme.of(context).scaffoldBackgroundColor,
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.outline),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary, width: 2),
                  ),
                ),
                controller: accountNumberController,
                keyboardType: TextInputType.number,
                obscureText: true,
                textInputAction: TextInputAction.next,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return AppLocalizations.of(context).accountNumberRequired;
                  } else if (value.length != 11) {
                    return AppLocalizations.of(context).validAccountNumber;
                  }
                  return null;
                },
              ),
              const SizedBox(height: 25),
              TextFormField(
                controller: confirmAccountNumberController,
                decoration: InputDecoration(
                  labelText: AppLocalizations.of(context).confirmAccountNumber,
                  // prefixIcon: Icon(Icons.person),
                  border: const OutlineInputBorder(),
                  isDense: true,
                  filled: true,
                  fillColor: Theme.of(context).scaffoldBackgroundColor,
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.outline),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary, width: 2),
                  ),
                ),
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.next,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return AppLocalizations.of(context).reenterAccountNumber;
                  }
                  if (value != accountNumberController.text) {
                    return AppLocalizations.of(context).accountMismatch;
                  }
                  return null;
                },
              ),
              if (!_isBeneficiaryValidated)
                Padding(
                  padding: const EdgeInsets.only(top: 12.0),
                  child: SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: _isValidating
                          ? null
                          : () {
                              if (accountNumberController.text.length == 11 &&
                                  confirmAccountNumberController.text ==
                                      accountNumberController.text) {
                                _validateBeneficiary();
                              } else {
                                setState(() {
                                  _validationError =
                                      AppLocalizations.of(context)
                                          .accountMismatch;
                                });
                              }
                            },
                      child: _isValidating
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : Text(
                              AppLocalizations.of(context).validateBeneficiary),
                    ),
                  ),
                ),
              if (_beneficiaryName != null && _isBeneficiaryValidated)
                Padding(
                  padding: const EdgeInsets.only(top: 12.0),
                  child: Row(
                    children: [
                      const Icon(Icons.check_circle, color: Colors.green),
                      const SizedBox(width: 8),
                      Text(
                        '${AppLocalizations.of(context).beneficiaryName}: $_beneficiaryName',
                        style: const TextStyle(
                            color: Colors.green, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
              if (_validationError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    _validationError!,
                    style: const TextStyle(color: Colors.red),
                  ),
                ),
              const SizedBox(height: 24),
              DropdownButtonFormField<String>(
                decoration: InputDecoration(
                  labelText: AppLocalizations.of(
                    context,
                  ).beneficiaryAccountType,
                  border: const OutlineInputBorder(),
                  isDense: true,
                  filled: true,
                  fillColor: Theme.of(context).scaffoldBackgroundColor,
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.outline),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary, width: 2),
                  ),
                ),
                value: _selectedAccountType,
                items: [
                  DropdownMenuItem(
                    value: 'SB',
                    child: Text(AppLocalizations.of(context).savings),
                  ),
                  DropdownMenuItem(
                    value: 'LN',
                    child: Text(AppLocalizations.of(context).loan),
                  ),
                ],
                onChanged: (value) {
                  setState(() {
                    _selectedAccountType = value;
                  });
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return AppLocalizations.of(context).selectAccountType;
                  }
                  return null;
                },
              ),
              const SizedBox(height: 25),
              TextFormField(
                decoration: InputDecoration(
                  labelText: AppLocalizations.of(context).amount,
                  border: const OutlineInputBorder(),
                  isDense: true,
                  filled: true,
                  fillColor: Theme.of(context).scaffoldBackgroundColor,
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.outline),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Theme.of(context).colorScheme.primary, width: 2),
                  ),
                ),
                controller: amountController,
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.next,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return AppLocalizations.of(context).amountRequired;
                  }
                  final amount = double.tryParse(value);
                  if (amount == null || amount <= 0) {
                    return AppLocalizations.of(context).validAmount;
                  }
                  return null;
                },
              ),
              const SizedBox(height: 45),
              Align(
                alignment: Alignment.center,
                child: SwipeButton.expand(
                  thumb: Icon(Icons.arrow_forward,
                      color: Theme.of(context).dialogBackgroundColor),
                  activeThumbColor: Theme.of(context).colorScheme.primary,
                  activeTrackColor: Theme.of(
                    context,
                  ).colorScheme.secondary.withAlpha(100),
                  borderRadius: BorderRadius.circular(30),
                  height: 56,
                  child: Text(
                    AppLocalizations.of(context).swipeToPay,
                    style: const TextStyle(fontSize: 16),
                  ),
                  onSwipe: () {
                    if (_formKey.currentState!.validate()) {
                      if (!_isBeneficiaryValidated) {
                        setState(() {
                          _validationError = AppLocalizations.of(context)
                              .validateBeneficiaryproceeding;
                        });
                        return;
                      }
                      // Perform payment logic
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => TransactionPinScreen(
                            onPinCompleted: (pinScreenContext, tpin) async {
                              final transfer = Transfer(
                                fromAccount: widget.debitAccount,
                                toAccount: accountNumberController.text,
                                toAccountType: _selectedAccountType!,
                                amount: amountController.text,
                                tpin: tpin,
                              );

                              final paymentService = getIt<PaymentService>();
                              final paymentResponseFuture = paymentService
                                  .processQuickPayWithinBank(transfer);

                              Navigator.of(pinScreenContext).pushReplacement(
                                MaterialPageRoute(
                                  builder: (_) => PaymentAnimationScreen(
                                      paymentResponse: paymentResponseFuture),
                                ),
                              );
                            },
                          ),
                        ),
                      );
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildTextFormField({
    required String label,
    required TextEditingController controller,
    TextInputType keyboardType = TextInputType.text,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      validator: validator,
      decoration: InputDecoration(
        labelText: label,
        border: const OutlineInputBorder(),
        isDense: true,
        filled: true,
        fillColor: Theme.of(context).dialogBackgroundColor,
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Theme.of(context).colorScheme.outline),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(
              color: Theme.of(context).colorScheme.primary, width: 2),
        ),
      ),
    );
  }
}
