import 'dart:async';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:kmobile/api/services/imps_service.dart';
import 'package:kmobile/api/services/limit_service.dart';
import 'package:kmobile/api/services/neft_service.dart';
import 'package:kmobile/api/services/rtgs_service.dart';
import 'package:kmobile/data/models/imps_transaction.dart';
import 'package:kmobile/data/models/neft_transaction.dart';
import 'package:kmobile/data/models/payment_response.dart';
import 'package:kmobile/data/models/rtgs_transaction.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart';
import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swipe_button/flutter_swipe_button.dart';
import '../../../../di/injection.dart';
import '../../../../api/services/beneficiary_service.dart';

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

  @override
  State<QuickPayOutsideBankScreen> createState() =>
      _QuickPayOutsideBankScreen();
}

class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
  final _formKey = GlobalKey<FormState>();
  final _limitService = getIt<LimitService>();
  Limit? _limit;
  bool _isLoadingLimit = true;
  final _formatCurrency = NumberFormat.currency(locale: 'en_IN', symbol: '₹');
  // Controllers
  final accountNumberController = TextEditingController();
  final confirmAccountNumberController = TextEditingController();
  final nameController = TextEditingController();
  final bankNameController = TextEditingController();
  final branchNameController = TextEditingController();
  final ifscController = TextEditingController();
  final phoneController = TextEditingController();
  final amountController = TextEditingController();
  final remarksController = TextEditingController();
  final _ifscFocusNode = FocusNode();
  final service = getIt<BeneficiaryService>();
  bool _isAmountOverLimit = false;

  late String accountType;
  bool _isValidating = false;
  bool _isBeneficiaryValidated = false;
  String? _validationError;

  @override
  void initState() {
    super.initState();
    _loadLimit();
    _ifscFocusNode.addListener(() {
      if (!_ifscFocusNode.hasFocus && ifscController.text.trim().length == 11) {
        _validateIFSC();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        accountType = 'Savings';
      });
    });
    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;
      });
    }
  }

// Add this method to check the amount against the limit
  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,
        ),
      );
    }

    if (_isAmountOverLimit != isOverLimit) {
      setState(() {
        _isAmountOverLimit = isOverLimit;
      });
    }
  }

  void _validateIFSC() async {
    final ifsc = ifscController.text.trim().toUpperCase();
    if (ifsc.isEmpty) return;

    try {
      final result = await service.validateIFSC(ifsc);

      if (mounted) {
        if (result.bankName.isEmpty) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(AppLocalizations.of(context).invalidIfsc)),
          );
          bankNameController.clear();
          branchNameController.clear();
        } else {
          bankNameController.text = result.bankName;
          branchNameController.text = result.branchName;
        }
      }
    } catch (e) {
      if (mounted) {
        final errorMessage = e.toString().toUpperCase();
        String snackbarMessage =
            AppLocalizations.of(context).somethingWentWrong;

        if (errorMessage.contains('INVALID') && errorMessage.contains('IFSC')) {
          snackbarMessage = AppLocalizations.of(context).invalidIfsc;
        }

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(snackbarMessage)),
        );
        bankNameController.clear();
        branchNameController.clear();
      }
    }
  }

  void _validateBeneficiary() async {
    FocusScope.of(context).unfocus();
    setState(() {
      _isValidating = true;
      _validationError = null;
      _isBeneficiaryValidated = false;
      nameController.text = ''; // clear previous name
    });

    final String accountNo = accountNumberController.text.trim();
    final String ifsc = ifscController.text.trim();
    final String remitter = "Unknown";

    final service = getIt<BeneficiaryService>();
    try {
      final String beneficiaryName = await service.validateBeneficiary(
        accountNo: accountNo,
        ifscCode: ifsc,
        remitterName: remitter,
      );

      setState(() {
        nameController.text = beneficiaryName;
        _isBeneficiaryValidated = true;
        _validationError = null;
      });
    } catch (e) {
      setState(() {
        _validationError = e.toString();
        _isBeneficiaryValidated = false;
      });
    } finally {
      if (mounted) {
        setState(() {
          _isValidating = false;
        });
      }
    }
  }

  List<String> transactionModes(BuildContext context) {
    return [
      AppLocalizations.of(context).neft,
      AppLocalizations.of(context).rtgs,
      AppLocalizations.of(context).imps,
    ];
  }

  int selectedTransactionIndex = 0;

  @override
  void dispose() {
    // Dispose controllers
    accountNumberController.dispose();
    confirmAccountNumberController.dispose();
    nameController.dispose();
    bankNameController.dispose();
    branchNameController.dispose();
    ifscController.dispose();
    phoneController.dispose();
    amountController.dispose();
    remarksController.dispose();
    super.dispose();
    _ifscFocusNode.dispose();
  }

  void _onProceedToPay() {
    if (_formKey.currentState!.validate()) {
      if (!_isBeneficiaryValidated) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
                  Text(AppLocalizations.of(context).plsValidateBeneficiary)),
        );
        return;
      }

      final amount = double.tryParse(amountController.text) ?? 0;
      final selectedMode = transactionModes(context)[selectedTransactionIndex];
      final isRtgs = selectedMode == AppLocalizations.of(context).rtgs;
      final isNeft = selectedMode == AppLocalizations.of(context).neft;
      final isImps = selectedMode == AppLocalizations.of(context).imps;

      if (isRtgs && amount < 200000) {
        showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Text(AppLocalizations.of(context).invalidRtgs),
            content: Text(AppLocalizations.of(context).invalidRtgsPopUp),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(ctx).pop(),
                child: Text(AppLocalizations.of(context).ok),
              ),
            ],
          ),
        );
        return;
      }

      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TransactionPinScreen(
            onPinCompleted: (pinScreenContext, tpin) async {
              if (isNeft) {
                // NEFT
                final neftTx = NeftTransaction(
                  fromAccount: widget.debitAccount,
                  toAccount: accountNumberController.text,
                  amount: amountController.text,
                  ifscCode: ifscController.text,
                  remitterName: "Unknown",
                  beneficiaryName: nameController.text,
                  tpin: tpin,
                  remarks: remarksController.text,
                );
                final neftService = getIt<NeftService>();
                final completer = Completer<PaymentResponse>();

                Navigator.of(pinScreenContext).pushReplacement(
                  MaterialPageRoute(
                    builder: (_) => PaymentAnimationScreen(
                        paymentResponse: completer.future),
                  ),
                );

                try {
                  final neftResponse =
                      await neftService.processNeftTransaction(neftTx);
                  final paymentResponse = PaymentResponse(
                    isSuccess: neftResponse.message.toUpperCase() == 'SUCCESS',
                    date: DateTime.now(),
                    creditedAccount: neftTx.toAccount,
                    amount: neftTx.amount,
                    currency: 'INR',
                    utr: neftResponse.utr,
                  );
                  completer.complete(paymentResponse);
                } on DioException catch (e) {
                  String errorMessage;
                  if (e.response != null && e.response!.data != null) {
                    try {
                      // final error = jsonDecode(e.response!.toString())['error'];
                      final error = e.response?.data['error'];
                      errorMessage = {
                            "INCORRECT_TPIN": "Please Enter the correct TPIN",
                            "INSUFFICIENT_FUNDS":
                                "Your account does not have sufficient balance"
                          }[error] ??
                          "Something Went Wrong";
                    } catch (_) {
                      errorMessage = "Something Went Wrong";
                    }
                  } else {
                    errorMessage = "Something Went Wrong";
                  }
                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: errorMessage,
                  );
                  completer.complete(paymentResponse);
                } catch (e) {
                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: e.toString(),
                  );
                  completer.complete(paymentResponse);
                }
              }

              if (isImps) {
                // IMPS
                final impsTx = ImpsTransaction(
                  fromAccount: widget.debitAccount,
                  toAccount: accountNumberController.text,
                  amount: amountController.text,
                  ifscCode: ifscController.text,
                  remitterName: "Unknown",
                  beneficiaryName: nameController.text,
                  tpin: tpin,
                  remarks: remarksController.text,
                );
                final impsService = getIt<ImpsService>();
                final completer = Completer<PaymentResponse>();
                if (!pinScreenContext.mounted) {
                  return;
                }

                Navigator.of(pinScreenContext).pushReplacement(
                  MaterialPageRoute(
                    builder: (_) => PaymentAnimationScreen(
                        paymentResponse: completer.future),
                  ),
                );

                try {
                  final impsResponse =
                      await impsService.processImpsTransaction(impsTx);
                  final paymentResponse = PaymentResponse(
                    isSuccess: impsResponse.message.toUpperCase() == 'SUCCESS',
                    date: DateTime.now(),
                    creditedAccount: impsTx.toAccount,
                    amount: impsTx.amount,
                    currency: 'INR',
                    utr: impsResponse.utr,
                  );
                  completer.complete(paymentResponse);
                } on DioException catch (e) {
                  final error = e.response?.data['error'];
                  var errorMessage = {
                        "INCORRECT_TPIN": "Please Enter the correct TPIN",
                        "INSUFFICIENT_FUNDS":
                            "Your account does not have sufficient balance"
                      }[error] ??
                      "Something Went Wrong";

                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: errorMessage,
                  );
                  completer.complete(paymentResponse);
                } catch (e) {
                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: e.toString(),
                  );
                  completer.complete(paymentResponse);
                }
              }

              if (isRtgs) {
                // RTGS
                final rtgsTx = RtgsTransaction(
                  fromAccount: widget.debitAccount,
                  toAccount: accountNumberController.text,
                  amount: amountController.text,
                  ifscCode: ifscController.text,
                  remitterName: "Unknown",
                  beneficiaryName: nameController.text,
                  tpin: tpin,
                  remarks: remarksController.text,
                );
                final rtgsService = getIt<RtgsService>();
                final completer = Completer<PaymentResponse>();
                if (!pinScreenContext.mounted) {
                  return;
                }
                Navigator.of(pinScreenContext).pushReplacement(
                  MaterialPageRoute(
                    builder: (_) => PaymentAnimationScreen(
                        paymentResponse: completer.future),
                  ),
                );

                try {
                  final rtgsResponse =
                      await rtgsService.processRtgsTransaction(rtgsTx);
                  final paymentResponse = PaymentResponse(
                    isSuccess: rtgsResponse.message.toUpperCase() == 'SUCCESS',
                    date: DateTime.now(),
                    creditedAccount: rtgsTx.toAccount,
                    amount: rtgsTx.amount,
                    currency: 'INR',
                    utr: rtgsResponse.utr,
                  );
                  completer.complete(paymentResponse);
                } on DioException catch (e) {
                  log('dio exception');

                  final error = e.response?.data['error'];
                  var errorMessage = {
                        "INCORRECT_TPIN": "Please Enter the correct TPIN",
                        "INSUFFICIENT_FUNDS":
                            "Your account does not have sufficient balance"
                      }[error] ??
                      "Something Went Wrong";

                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: errorMessage,
                  );
                  completer.complete(paymentResponse);
                } catch (e) {
                  final paymentResponse = PaymentResponse(
                    isSuccess: false,
                    errorMessage: e.toString(),
                  );
                  completer.complete(paymentResponse);
                }
              }
            },
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          AppLocalizations.of(context).quickPayOutsideBank,
        ),
        centerTitle: false,
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(12),
            child: Form(
              key: _formKey,
              child: ListView(
                children: [
                  const SizedBox(height: 10),
                  Text(
                    AppLocalizations.of(context).debitFrom,
                    style: Theme.of(context).textTheme.titleSmall,
                  ),
                  Card(
                    elevation: 0,
                    margin: const EdgeInsets.symmetric(vertical: 8.0),
                    child: ListTile(
                      leading: Image.asset(
                        'assets/images/logo.png',
                        width: 40,
                        height: 40,
                      ),
                      title: Text(widget.debitAccount),
                      subtitle: Text(AppLocalizations.of(context).ownBank),
                    ),
                  ),
                  const SizedBox(height: 24),
                  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,
                    onChanged: (value) {
                      nameController.clear();
                      setState(() {
                        _isBeneficiaryValidated = false;
                      });
                    },
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return AppLocalizations.of(context)
                            .accountNumberRequired;
                      } else if (value.length < 7 || value.length > 20) {
                        return AppLocalizations.of(context).accno7to20;
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 24),
                  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;
                    },
                  ),
                  const SizedBox(height: 25),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: TextFormField(
                          focusNode: _ifscFocusNode,
                          maxLength: 11,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(11),
                          ],
                          decoration: InputDecoration(
                            labelText: AppLocalizations.of(context).ifscCode,
                            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: ifscController,
                          textInputAction: TextInputAction.next,
                          onChanged: (value) {
                            setState(() {
                              final trimmed = value.trim().toUpperCase();
                              if (trimmed.length < 11) {
                                // clear bank/branch if backspace or changed
                                bankNameController.clear();
                                branchNameController.clear();
                              }
                            });
                          },
                          validator: (value) {
                            final pattern = RegExp(r'^[A-Z]{4}0[A-Z0-9]{6}$');
                            if (value == null || value.trim().isEmpty) {
                              return AppLocalizations.of(context).enterIfsc;
                            } else if (!pattern.hasMatch(
                              value.trim().toUpperCase(),
                            )) {
                              return AppLocalizations.of(
                                context,
                              ).invalidIfscFormat;
                            }
                            return null;
                          },
                        ),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        child: DropdownButtonFormField<String>(
                          value: accountType,
                          decoration: InputDecoration(
                            labelText: AppLocalizations.of(context).accountType,
                            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),
                            ),
                          ),
                          items: [
                            'Savings',
                            'Current',
                          ]
                              .map(
                                (e) =>
                                    DropdownMenuItem(value: e, child: Text(e)),
                              )
                              .toList(),
                          onChanged: (value) => setState(() {
                            accountType = value!;
                          }),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 25),
                  TextFormField(
                    controller: bankNameController,
                    enabled: false,
                    decoration: InputDecoration(
                      labelText: AppLocalizations.of(context).bankName,
                      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),
                      ),
                    ),
                  ),
                  const SizedBox(height: 25),
                  TextFormField(
                    controller: branchNameController,
                    enabled: false,
                    decoration: InputDecoration(
                      labelText: AppLocalizations.of(context).branchName,
                      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,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  if (!_isBeneficiaryValidated)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 24),
                      child: SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed:
                              _isValidating || ifscController.text.length != 11
                                  ? null
                                  : () {
                                      if (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 (_validationError != null)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 24.0),
                      child: Text(
                        _validationError!,
                        style: TextStyle(
                            color: Theme.of(context).colorScheme.error),
                      ),
                    ),
                  TextFormField(
                    controller: nameController,
                    enabled: false,
                    decoration: InputDecoration(
                      labelText: AppLocalizations.of(context).name,
                      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),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return AppLocalizations.of(context).nameRequired;
                      }
                      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),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              controller: phoneController,
                              keyboardType: TextInputType.phone,
                              decoration: InputDecoration(
                                labelText: AppLocalizations.of(context).phone,
                                prefixIcon: const Icon(Icons.phone),
                                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),
                                ),
                              ),
                              textInputAction: TextInputAction.next,
                              validator: (value) => value == null ||
                                      value.isEmpty
                                  ? AppLocalizations.of(context).phoneRequired
                                  : null,
                            ),
                          ),
                          const SizedBox(width: 10),
                          Expanded(
                            child: 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 Padding(
                      padding: EdgeInsets.only(left: 8.0),
                      child: Text('Fetching daily limit...'),
                    ),
                  if (!_isLoadingLimit && _limit != null)
                    Padding(
                      padding: const EdgeInsets.only(left: 8.0),
                      child: Text(
                        'Remaining Daily Limit: ${_formatCurrency.format(_limit!.dailyLimit - _limit!.usedLimit)}',
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    ),
                  const SizedBox(height: 30),
                  Row(
                    children: [
                      Text(
                        AppLocalizations.of(context).transactionMode,
                        style: const TextStyle(fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(width: 12),
                      Expanded(child: buildTransactionModeSelector()),
                    ],
                  ),
                  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,
                      onSwipe: () {
                        if (_isAmountOverLimit) {
                          return; // Do nothing if amount is over the limit
                        }
                        _onProceedToPay();
                      },
                      child: Text(
                        AppLocalizations.of(context).swipeToPay,
                        style: const TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          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 buildTransactionModeSelector() {
    return Container(
      padding: const EdgeInsets.all(4),
      child: Row(
        children: List.generate(transactionModes(context).length, (index) {
          bool isSelected = selectedTransactionIndex == index;
          return Expanded(
            child: GestureDetector(
              onTap: () {
                setState(() => selectedTransactionIndex = index);
              },
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 4),
                padding: const EdgeInsets.symmetric(vertical: 5),
                decoration: BoxDecoration(
                  color: isSelected
                      ? Theme.of(context).colorScheme.primary
                      : Theme.of(context).scaffoldBackgroundColor,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(
                    color: isSelected
                        ? Theme.of(context).colorScheme.primary
                        : Theme.of(context).scaffoldBackgroundColor,
                    width: isSelected ? 0 : 1.2,
                  ),
                ),
                alignment: Alignment.center,
                child: Text(
                  transactionModes(context)[index],
                  style:
                      TextStyle(color: Theme.of(context).colorScheme.onSurface),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }
}
