import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_swipe_button/flutter_swipe_button.dart';
import 'package:intl/intl.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/api/services/limit_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 _limitService = getIt<LimitService>();
  Limit? _limit;
  bool _isLoadingLimit = true;
  final _formatCurrency = NumberFormat.currency(locale: 'en_IN', symbol: '₹');
  final TextEditingController accountNumberController = TextEditingController();
  final TextEditingController confirmAccountNumberController =
      TextEditingController();
  final TextEditingController amountController = TextEditingController();
  final TextEditingController remarksController = TextEditingController();
  String? _selectedAccountType;
  bool _isAmountOverLimit = false;
  String? _beneficiaryName;
  bool _isValidating = false;
  bool _isBeneficiaryValidated = false;
  String? _validationError;

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

  Future<void> _loadLimit() async {
    setState(() {
      _isLoadingLimit = true;
    });
    try {
      final limitData = await _limitService.getLimit();
      setState(() {
        _limit = limitData;
        _isLoadingLimit = false;
      });
    } catch (e) {
      // Handle error if needed
      setState(() {
        _isLoadingLimit = false;
      });
    }
  }

  void _checkAmountLimit() {
    if (_limit == null) return;

    final amount = double.tryParse(amountController.text) ?? 0;
    final remainingLimit = _limit!.dailyLimit - _limit!.usedLimit;
    final bool isOverLimit = amount > remainingLimit;

    if (isOverLimit) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
              'Amount exceeds remaining daily limit of ${_formatCurrency.format(remainingLimit)}'),
          backgroundColor: Colors.red,
        ),
      );
    }

    // Update state only if it changes to avoid unnecessary rebuilds
    if (_isAmountOverLimit != isOverLimit) {
      setState(() {
        _isAmountOverLimit = isOverLimit;
      });
    }
  }

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

  @override
  void dispose() {
    amountController.removeListener(_checkAmountLimit);
    accountNumberController.removeListener(_resetBeneficiaryValidation);
    confirmAccountNumberController.removeListener(_resetBeneficiaryValidation);
    accountNumberController.dispose();
    confirmAccountNumberController.dispose();
    amountController.dispose();
    remarksController.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,
        ),
        centerTitle: false,
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Form(
              key: _formKey,
              child: SingleChildScrollView(
                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(
                      controller: remarksController,
                      decoration: InputDecoration(
                        labelText: AppLocalizations.of(context).remarks,
                        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),
                        ),
                      ),
                    ),
                    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: 8),
                    if (_isLoadingLimit) const Text('Fetching daily limit...'),
                    if (!_isLoadingLimit && _limit != null)
                      Text(
                        'Remaining Daily Limit: ${_formatCurrency.format(_limit!.dailyLimit - _limit!.usedLimit)}',
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    const SizedBox(height: 45),
                    Align(
                      alignment: Alignment.center,
                      child: SwipeButton.expand(
                        thumb: Icon(Icons.arrow_forward,
                            color: _isAmountOverLimit
                                ? Colors.grey
                                : Theme.of(context).dialogBackgroundColor),
                        activeThumbColor: _isAmountOverLimit
                            ? Colors.grey.shade700
                            : Theme.of(context).colorScheme.primary,
                        activeTrackColor: _isAmountOverLimit
                            ? Colors.grey.shade300
                            : 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 (_isAmountOverLimit) {
                            return; // Do nothing if amount is over limit
                          }
                          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,
                                      remarks: remarksController.text,
                                    );

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

                                    Navigator.of(pinScreenContext)
                                        .pushReplacement(
                                      MaterialPageRoute(
                                        builder: (_) => PaymentAnimationScreen(
                                            paymentResponse:
                                                paymentResponseFuture),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            );
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          IgnorePointer(
            child: Center(
              child: Opacity(
                opacity: 0.07, // Reduced opacity
                child: ClipOval(
                  child: Image.asset(
                    'assets/images/logo.png',
                    width: 200, // Adjust size as needed
                    height: 200, // Adjust size as needed
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  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),
        ),
      ),
    );
  }
}
