import 'package:flutter/material.dart';
import 'package:intl/intl.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/data/models/user.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart';
import 'package:kmobile/l10n/app_localizations.dart';
import 'package:kmobile/widgets/bank_logos.dart';

class FundTransferSelfAmountScreen extends StatefulWidget {
  final String debitAccountNo;
  final User creditAccount;
  final String remitterName;

  const FundTransferSelfAmountScreen({
    super.key,
    required this.debitAccountNo,
    required this.creditAccount,
    required this.remitterName,
  });

  @override
  State<FundTransferSelfAmountScreen> createState() =>
      _FundTransferSelfAmountScreenState();
}

class _FundTransferSelfAmountScreenState
    extends State<FundTransferSelfAmountScreen> {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();
  final _remarksController = TextEditingController();

  // --- Limit Checking Variables ---
  final _limitService = getIt<LimitService>();
  Limit? _limit;
  bool _isLoadingLimit = true;
  bool _isAmountOverLimit = false;
  final _formatCurrency = NumberFormat.currency(locale: 'en_IN', symbol: '₹');

  @override
  void initState() {
    super.initState();
    _loadLimit(); // Fetch the daily limit
    _amountController
        .addListener(_checkAmountLimit); // Listen for amount changes
  }

  @override
  void dispose() {
    _amountController.removeListener(_checkAmountLimit);
    _amountController.dispose();
    _remarksController.dispose();
    super.dispose();
  }

  Future<void> _loadLimit() async {
    setState(() {
      _isLoadingLimit = true;
    });
    try {
      final limitData = await _limitService.getLimit();
      setState(() {
        _limit = limitData;
        _isLoadingLimit = false;
      });
    } catch (e) {
      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) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        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 _onProceed() {
    if (_formKey.currentState!.validate()) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TransactionPinScreen(
            onPinCompleted: (pinScreenContext, tpin) async {
              final transfer = Transfer(
                fromAccount: widget.debitAccountNo,
                toAccount: widget.creditAccount.accountNo!,
                toAccountType: 'Savings', // Assuming 'SB' for savings
                amount: _amountController.text,
                tpin: tpin,
              );

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).fundTransferTitle),
      ),
      body: SafeArea(
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Debit Account (User)
                    Text(
                      AppLocalizations.of(context).debitFromLabel,
                      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.remitterName),
                        subtitle: Text(widget.debitAccountNo),
                      ),
                    ),
                    const SizedBox(height: 24),

                    // Credit Account (Self)
                    Text(
                      AppLocalizations.of(context).creditedTo,
                      style: Theme.of(context).textTheme.titleSmall,
                    ),
                    Card(
                      elevation: 0,
                      margin: const EdgeInsets.symmetric(vertical: 8.0),
                      child: ListTile(
                        leading: getBankLogo(
                            'Kangra Central Co-operative Bank', context),
                        title: Text(widget.creditAccount.name ?? 'N/A'),
                        subtitle: Text(widget.creditAccount.accountNo ?? 'N/A'),
                      ),
                    ),
                    const SizedBox(height: 24),

                    // Remarks
                    TextFormField(
                      controller: _remarksController,
                      decoration: InputDecoration(
                        labelText:
                            AppLocalizations.of(context).remarksOptionalHint,
                        border: const OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 24),

                    // Amount
                    TextFormField(
                      controller: _amountController,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: AppLocalizations.of(context).amountLabel,
                        border: const OutlineInputBorder(),
                        prefixIcon: const Icon(Icons.currency_rupee),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return AppLocalizations.of(context).amountRequired;
                        }
                        if (double.tryParse(value) == null ||
                            double.parse(value) <= 0) {
                          return AppLocalizations.of(context).validAmountError;
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 8),

                    // Daily Limit Display
                    if (_isLoadingLimit)
                      Text(AppLocalizations.of(context)
                          .fetchingDailyLimitLoader),
                    if (!_isLoadingLimit && _limit != null)
                      Text(
                        '${AppLocalizations.of(context).remainingDailyLimit} ${_formatCurrency.format(_limit!.dailyLimit - _limit!.usedLimit)}',
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    const Spacer(),

                    // Proceed Button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _isAmountOverLimit ? null : _onProceed,
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                        ),
                        child: Text(AppLocalizations.of(context).proceedButton),
                      ),
                    ),
                    const SizedBox(height: 10),
                  ],
                ),
              ),
            ),
            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
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
