import 'package:flutter/material.dart';
import 'package:kmobile/features/fund_transfer/screens/cooldown.dart';
import 'package:kmobile/widgets/bank_logos.dart';
import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/features/fund_transfer/screens/fund_transfer_amount_screen.dart';
import '../../../l10n/app_localizations.dart';
import '../../../di/injection.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:shimmer/shimmer.dart';

class FundTransferBeneficiaryScreen extends StatefulWidget {
  final String creditAccountNo;
  final String remitterName;
  final bool isOwnBank;
  const FundTransferBeneficiaryScreen(
      {super.key,
      required this.creditAccountNo,
      required this.remitterName,
      required this.isOwnBank});

  @override
  State<FundTransferBeneficiaryScreen> createState() =>
      _FundTransferBeneficiaryScreenState();
}

class _FundTransferBeneficiaryScreenState
    extends State<FundTransferBeneficiaryScreen> {
  var service = getIt<BeneficiaryService>();
  bool _isLoading = true;
  List<Beneficiary> _beneficiaries = [];
  List<Beneficiary> _filteredBeneficiaries = [];
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadBeneficiaries();
    _searchController.addListener(() {
      _filterBeneficiaries(_searchController.text);
    });
  }

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

  Future<void> _loadBeneficiaries() async {
    final data = await service.fetchBeneficiaryList();
    setState(() {
      _beneficiaries = data
          .where((b) => widget.isOwnBank
              ? b.bankName!.toLowerCase().contains('kangra central')
              : !b.bankName!.toLowerCase().contains('kangra central'))
          .toList();
      _filteredBeneficiaries = _beneficiaries;
      _isLoading = false;
    });
  }

  void _filterBeneficiaries(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredBeneficiaries = _beneficiaries;
      } else {
        _filteredBeneficiaries = _beneficiaries.where((beneficiary) {
          final lowerQuery = query.toLowerCase();
          return beneficiary.name.toLowerCase().contains(lowerQuery) ||
              beneficiary.accountNo.toLowerCase().contains(lowerQuery);
        }).toList();
      }
    });
  }

  Widget _buildShimmerList() {
    return ListView.builder(
      itemCount: 6,
      itemBuilder: (context, index) => Shimmer.fromColors(
        baseColor: Colors.grey.shade300,
        highlightColor: Colors.grey.shade100,
        child: ListTile(
          leading: const CircleAvatar(
            radius: 24,
            backgroundColor: Colors.white,
          ),
          title: Container(
            height: 16,
            color: Colors.white,
            margin: const EdgeInsets.symmetric(vertical: 4),
          ),
          subtitle: Container(
            height: 14,
            color: Colors.white,
            margin: const EdgeInsets.symmetric(vertical: 4),
          ),
        ),
      ),
    );
  }

  Widget _buildBeneficiaryList() {
    if (_filteredBeneficiaries.isEmpty) {
      return Center(
          child: Text(AppLocalizations.of(context).noBeneficiaryFound));
    }
    return ListView.builder(
      itemCount: _filteredBeneficiaries.length,
      itemBuilder: (context, index) {
        final beneficiary = _filteredBeneficiaries[index];

        // --- Cooldown Logic ---
        bool isCoolingDown = false;
        if (beneficiary.createdAt != null) {
          final sixtyMinutesAgo =
              DateTime.now().subtract(const Duration(minutes: 60));
          isCoolingDown = beneficiary.createdAt!.isAfter(sixtyMinutesAgo);
        }
        // --- End of Cooldown Logic ---

        // By wrapping the ListTile in an Opacity widget, we can make it look
        // disabled while ensuring the onTap callback still works.
        return Card(
          margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
          child: Opacity(
            opacity: isCoolingDown ? 0.5 : 1.0,
            child: ListTile(
              // REMOVED the 'enabled' property from here.
              leading: CircleAvatar(
                radius: 24,
                backgroundColor: Colors.transparent,
                child: getBankLogo(beneficiary.bankName, context),
              ),
              title: Text(beneficiary.name),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(beneficiary.accountNo),
                  if (beneficiary.bankName != null &&
                      beneficiary.bankName!.isNotEmpty)
                    Text(
                      beneficiary.bankName!,
                      style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                    ),
                ],
              ),
              trailing: isCoolingDown
                  ? CooldownTimer(
                      createdAt: beneficiary.createdAt!,
                      onTimerFinish: () {
                        setState(() {});
                      },
                    )
                  : null,
              onTap: () {
                if (isCoolingDown) {
                  // This will now execute correctly on tap
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text(
                          'Beneficiary will be enabled after the cooldown period.'),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                } else {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FundTransferAmountScreen(
                        debitAccountNo: widget.creditAccountNo,
                        creditBeneficiary: beneficiary,
                        remitterName: widget.remitterName,
                        isOwnBank: widget.isOwnBank,
                      ),
                    ),
                  );
                }
              },
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).beneficiaries),
      ),
      body: Stack(
        children: [
          Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText:
                        AppLocalizations.of(context).searchByNameOrAccountHint,
                    prefixIcon: const Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                ),
              ),
              Expanded(
                child:
                    _isLoading ? _buildShimmerList() : _buildBeneficiaryList(),
              ),
            ],
          ),
          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
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
