import 'package:kmobile/data/models/user.dart';
import 'package:kmobile/di/injection.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/api/services/cheque_service.dart';
import 'package:kmobile/features/cheque/screens/revoke%20_stop_multiple_screen.dart';
import 'package:kmobile/features/cheque/screens/revoke_stop_single_screen.dart';
import 'package:kmobile/l10n/app_localizations.dart';

class RevokeStopChequeScreen extends StatefulWidget {
  final List<User> users;
  final int selectedIndex;

  const RevokeStopChequeScreen(
      {
        super.key,
        required this.users,
        required this.selectedIndex,
    });

  @override
  State<RevokeStopChequeScreen> createState() => _RevokeStopChequeScreenState();
}

class _RevokeStopChequeScreenState extends State<RevokeStopChequeScreen> {
  User? _selectedAccount;
  var service = getIt<ChequeService>();
  bool _isLoading = true;
  List<Cheque> _stCheques = [];
  List<User> _filteredUsers = [];
  String? _ciFromCheque;
  String? _ciToCheque;

  @override
  void initState() {
    super.initState();
    _filteredUsers = widget.users
        .where((user) => ['SA', 'SB', 'CA', 'CC'].contains(user.accountType))
        .toList();

    if (widget.users.isNotEmpty && widget.selectedIndex < widget.users.length) {
      if (_filteredUsers.isNotEmpty) {
        if (_filteredUsers.contains(widget.users[widget.selectedIndex])) {
          _selectedAccount = widget.users[widget.selectedIndex];
        } else {
          _selectedAccount = _filteredUsers.first;
        }
      } else {
        _selectedAccount = widget.users[widget.selectedIndex];
      }
    } else {
      if (_filteredUsers.isNotEmpty) {
        _selectedAccount = _filteredUsers.first;
      }
    }

    _loadCheques();
  }

  Future<void> _loadCheques() async {
    if (_selectedAccount == null) {
      setState(() {
        _isLoading = false;
        _stCheques = [];
      });
      return;
    }
    setState(() {
      _isLoading = true;
    });

    String instrType;
    switch (_selectedAccount!.accountType) {
      case 'SA':
      case 'SB':
        instrType = '10';
        break;
      case 'CA':
        instrType = '11';
        break;
      case 'CC':
        instrType = '13';
        break;
      default:
        instrType = '10';
    }

    try {
      final data = await service.ChequeEnquiry(
          accountNumber: _selectedAccount!.accountNo!, instrType: instrType);
      final stCheques = data.where((cheque) => cheque.type == 'ST').toList();
      final ciCheque = data.where((cheque) => cheque.type == 'CI').toList();
      setState(() {
        _stCheques = stCheques;
        if (ciCheque.isNotEmpty) {
          _ciFromCheque = ciCheque.first.fromCheque;
          _ciToCheque = ciCheque.first.toCheque;
        } else {
          _ciFromCheque = null;
          _ciToCheque = null;
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _stCheques = [];
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to fetch cheque status: ${e.toString()}'),
        ),
      );
    }
  }

  String _getAccountTypeDisplayName(String accountType) {
    switch (accountType.toLowerCase()) {
      case 'sa':
        return AppLocalizations.of(context).savingsAccount;
      case 'sb':
        return AppLocalizations.of(context).savingsAccount;
      case 'ca':
        return "Current Account";
      case 'cc':
        return "Cash Credit Account";
      default:
        return accountType;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).revokeStop),
        centerTitle: false,
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(children: [
              Card(
                elevation: 4,
                margin: const EdgeInsets.symmetric(vertical: 8.0),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        AppLocalizations.of(context).accountNumber,
                        style: const TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      const SizedBox(width: 16),
                      if (_selectedAccount != null)
                        Expanded(
                          child: DropdownButton<User>(
                            value: _selectedAccount,
                            onChanged: (User? newUser) {
                              if (newUser != null) {
                                setState(() {
                                  _selectedAccount = newUser;
                                  _loadCheques();
                                });
                              }
                            },
                            items: _filteredUsers.map((user) {
                              return DropdownMenuItem<User>(
                                value: user,
                                child: Text(user.accountNo.toString()),
                              );
                            }).toList(),
                          ),
                        )
                      else
                        Text(AppLocalizations.of(context).noAccountsFound),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20),
              Row(
                children: [
                  Expanded(
                    child: Card(
                      color: Theme.of(context).colorScheme.primaryContainer,
                      elevation: 4,
                      child: InkWell(
                        onTap: () {
                          if (_selectedAccount != null &&
                              _stCheques.isNotEmpty) {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) =>
                                    RevokeStopSingleChequeScreen(
                                  selectedAccount: _selectedAccount!,
                                  date: _stCheques.first.Date!,
                                  instrType: _stCheques.first.InstrType!,
                                  fromCheque: _ciFromCheque ?? _stCheques.first.fromCheque!,
                                  toCheque: _ciToCheque ?? _stCheques.first.toCheque!,
                                ),
                              ),
                            );
                          } else {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text("No stopped cheques present"),
                              ),
                            );
                          }
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Center(
                            child: Text(
                              AppLocalizations.of(context).revokeSingleStopTitle,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context)
                                    .colorScheme
                                    .onPrimaryContainer,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Card(
                      color: Theme.of(context).colorScheme.primaryContainer,
                      elevation: 4,
                      child: InkWell(
                        onTap: () {
                          if (_selectedAccount != null &&
                              _stCheques.isNotEmpty) {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) =>
                                    RevokeStopMultipleChequesScreen(
                                  selectedAccount: _selectedAccount!,
                                  date: _stCheques.first.Date!,
                                  instrType: _stCheques.first.InstrType!,
                                  fromCheque: _ciFromCheque ?? _stCheques.first.fromCheque!,
                                  toCheque: _ciToCheque ?? _stCheques.first.toCheque!,
                                ),
                              ),
                            );
                          } else {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text(AppLocalizations.of(context)
                                    .pleaseSelectAccountFirst),
                              ),
                            );
                          }
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Center(
                            child: Text(
                             AppLocalizations.of(context).revokeMultipleStops,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context)
                                    .colorScheme
                                    .onSecondaryContainer,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              Expanded(
                child: _isLoading
                    ? const Center(child: CircularProgressIndicator())
                    : _stCheques.isEmpty
                        ? Center(
                            child: Text(AppLocalizations.of(context)
                                .noChequeIssuedStatus))
                        : ListView.builder(
                            itemCount: _stCheques.length,
                            itemBuilder: (context, index) {
                              return _buildSTTile(context, _stCheques[index]);
                            },
                          ),
              ),
            ]),
          ),
          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 _buildSTTile(BuildContext context, Cheque cheque) {
    return Card(
      margin: const EdgeInsets.symmetric(
        vertical: 8.0,
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(AppLocalizations.of(context).stopChequeLabel,
                style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            _buildInfoRow('From Cheque:', cheque.fromCheque),
            _buildInfoRow('To Cheque:', cheque.toCheque),
            _buildInfoRow('Account Type:',
                _getAccountTypeDisplayName(_selectedAccount!.accountType!)),
            _buildInfoRow('Branch Code:', cheque.branchCode),
            _buildInfoRow('Stop Issue Date:', cheque.stopIssueDate),
            _buildInfoRow('Stop Expiry Date:', cheque.StopExpiryDate),
            _buildInfoRow('Cheques Count:', cheque.Chequescount),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          Text(value ?? ''),
        ],
      ),
    );
  }
}
