import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/widgets/bank_logos.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';

import '../../../l10n/app_localizations.dart';

class BeneficiaryDetailsScreen extends StatefulWidget {
  final Beneficiary beneficiary;

  const BeneficiaryDetailsScreen({super.key, required this.beneficiary});

  @override
  State<BeneficiaryDetailsScreen> createState() =>
      _BeneficiaryDetailsScreenState();
}

class _BeneficiaryDetailsScreenState extends State<BeneficiaryDetailsScreen> {
  final service = getIt<BeneficiaryService>();
  late String _currentLimit;
  final _limitController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _currentLimit = (widget.beneficiary.transactionLimit == null ||
            widget.beneficiary.transactionLimit!.isEmpty)
        ? 'N/A'
        : widget.beneficiary.transactionLimit!;
  }

  @override
  void dispose() {
    _limitController.dispose();
    super.dispose();
  }

  void _deleteBeneficiary(BuildContext context) async {
    try {
      await service.deleteBeneficiary(widget.beneficiary.accountNo);
      if (!context.mounted) {
        return;
      }
      _showSuccessDialog(context);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                '${AppLocalizations.of(context).failedToDeleteBeneficiary} : $e')),
      );
    }
  }

  void _showSuccessDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(AppLocalizations.of(context).success),
          content:
              Text(AppLocalizations.of(context).beneficiaryDeletedSuccessfully),
          actions: <Widget>[
            TextButton(
              child: Text(AppLocalizations.of(context).ok),
              onPressed: () {
                Navigator.of(context).popUntil((route) => route.isFirst);
              },
            ),
          ],
        );
      },
    );
  }

  void _showDeleteConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(AppLocalizations.of(context).deleteBeneficiary),
          content: Text(AppLocalizations.of(context)
              .areYouSureYouWantToDeleteThisBeneficiary),
          actions: <Widget>[
            TextButton(
              child: Text(AppLocalizations.of(context).cancel),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text(AppLocalizations.of(context).delete),
              onPressed: () {
                _deleteBeneficiary(context);
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _showEditLimitDialog() async {
    _limitController.text = _currentLimit == 'N/A' ? '' : _currentLimit;
    await showDialog(
      context: context,
      builder: (dialogContext) {
        final localizations = AppLocalizations.of(dialogContext);
        final theme = Theme.of(dialogContext);
        return AlertDialog(
          title: Text(localizations.editLimit),
          content: TextField(
            controller: _limitController,
            autofocus: true,
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'^\d+')),
            ],
            decoration: InputDecoration(
              labelText: localizations.limitAmount,
              prefixText: '₹',
              border: const OutlineInputBorder(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(dialogContext).pop(),
              child: Text(localizations.cancel),
            ),
            ElevatedButton(
              onPressed: () async {
                final value = _limitController.text;
                if (value.isEmpty || int.tryParse(value) == null) return;

                try {
                  await service.updateLimit(
                    beneficiaryAccountNo: widget.beneficiary.accountNo,
                    newLimit: value,
                  );
                  if (!mounted) return;
                  setState(() {
                    _currentLimit = value;
                  });
                  Navigator.of(dialogContext).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text(localizations.limitUpdatedSuccess),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                } catch (e) {
                  Navigator.of(dialogContext).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text("${localizations.error}: $e"),
                      behavior: SnackBarBehavior.floating,
                      backgroundColor: theme.colorScheme.error,
                    ),
                  );
                }
              },
              child: Text(localizations.save),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).beneficiarydetails),
      ),
      body: SafeArea(
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 24,
                        backgroundColor: Colors.transparent,
                        child: getBankLogo(widget.beneficiary.bankName, context),
                      ),
                      const SizedBox(width: 16),
                      Text(
                        widget.beneficiary.name,
                        style: const TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  const SizedBox(height: 24),
                  _buildDetailRow('${AppLocalizations.of(context).bankName} ',
                      widget.beneficiary.bankName ?? 'N/A'),
                  _buildDetailRow(
                      '${AppLocalizations.of(context).accountNumber} ',
                      widget.beneficiary.accountNo),
                  _buildDetailRow(
                      '${AppLocalizations.of(context).accountType} ',
                      widget.beneficiary.accountType),
                  _buildDetailRow('${AppLocalizations.of(context).ifscCode} ',
                      widget.beneficiary.ifscCode),
                  _buildDetailRow('${AppLocalizations.of(context).branchName} ',
                      widget.beneficiary.branchName ?? 'N/A'),
                  _buildDetailRow(
                      "Beneficiary Transactional Limit", _currentLimit),
                  const Spacer(),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      ElevatedButton.icon(
                        onPressed: _showEditLimitDialog,
                        icon: const Icon(Icons.currency_rupee),
                        label: Text(AppLocalizations.of(context).editLimit),
                      ),
                      ElevatedButton.icon(
                        onPressed: () {
                          // Delete beneficiary option
                          _showDeleteConfirmationDialog(context);
                        },
                        icon: const Icon(Icons.delete),
                        label: Text(AppLocalizations.of(context).delete),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            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 _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 16),
          Flexible(
            child: Text(
              value,
              textAlign: TextAlign.end,
            ),
          ),
        ],
      ),
    );
  }
}

