import 'package:flutter/material.dart';
import 'package:kmobile/features/cheque/screens/stop_multiple_cheques_screen.dart';
import 'package:kmobile/features/cheque/screens/stop_single_cheque_screen.dart';
import 'package:kmobile/api/services/cheque_service.dart';
import 'package:kmobile/data/models/user.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/l10n/app_localizations.dart';

class StopChequeScreen extends StatefulWidget {
  final List<User> users;
  final int selectedIndex;
  const StopChequeScreen({
    super.key,
    required this.users,
    required this.selectedIndex,
  });

  @override
  State<StopChequeScreen> createState() => _StopChequeScreenState();
}

class _StopChequeScreenState extends State<StopChequeScreen> {
  User? _selectedAccount;
  var service = getIt<ChequeService>();
  bool _isLoading = true;
  Cheque? _ciCheque;
  List<User> _filteredUsers = [];

  @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;
        _ciCheque = null;
      });
      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 ciCheques = data.where((cheque) => cheque.type == 'CI').toList();
      setState(() {
        _ciCheque = ciCheques.isNotEmpty ? ciCheques.first : null;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _ciCheque = null;
      });
      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).stopChequeTitle),
        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 && _ciCheque != null) {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => StopSingleChequeScreen(
                                    selectedAccount: _selectedAccount!,
                                    date: _ciCheque!.Date!,
                                    instrType: _ciCheque!.InstrType!,
                                    fromCheque: _ciCheque!.fromCheque!,
                                    toCheque: _ciCheque!.toCheque!,
                                  ),
                                ),
                              );
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  content: Text(AppLocalizations.of(context)
                                      .noChequebookToStop),
                                ),
                              );
                            }
                          },
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Center(
                              child: Text(
                                AppLocalizations.of(context)
                                    .stopSingleChequeTitle,
                                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) {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) =>
                                      StopMultipleChequesScreen(
                                    selectedAccount: _selectedAccount!,
                                    date: _ciCheque!.Date!,
                                    instrType: _ciCheque!.InstrType!,
                                    fromCheque: _ciCheque!.fromCheque!,
                                    toCheque: _ciCheque!.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)
                                    .stopMultipleChequesButton,
                                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())
                      : _ciCheque == null
                          ? Center(
                              child: Text(AppLocalizations.of(context)
                                  .noChequeIssuedStatus))
                          : _buildCiTile(context, _ciCheque!),
                ),
              ],
            ),
          ),
          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 _buildCiTile(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).chequebookDetailsTitle,
                style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            _buildInfoRow('Account Number:', _selectedAccount!.accountNo!),
            _buildInfoRow('Customer Name:', _selectedAccount!.name!),
            _buildInfoRow('CIF Number:', _selectedAccount!.cifNumber!),
            _buildInfoRow('Account Type:',
                _getAccountTypeDisplayName(_selectedAccount!.accountType!)),
            _buildInfoRow('Branch Code:', cheque.branchCode),
            _buildInfoRow('Starting Cheque Number:', cheque.fromCheque),
            _buildInfoRow('Ending Cheque Number:', cheque.toCheque),
            _buildInfoRow('Issue Date:', cheque.Date),
            _buildInfoRow('Number of Cheques:', cheque.Chequescount),
            _buildInfoRow('Instrument Type:', cheque.InstrType),
          ],
        ),
      ),
    );
  }

  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 ?? ''),
        ],
      ),
    );
  }
}
