import 'package:flutter/material.dart';
import 'package:kmobile/api/services/yojna_service.dart';
import 'package:kmobile/data/models/user.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/yojna/screens/pmjjby_screen.dart';
import 'package:kmobile/features/yojna/screens/pmsby_screen.dart';
import 'package:kmobile/features/yojna/screens/pmjjby_enquiry_screen.dart';
import 'package:kmobile/features/yojna/screens/pmsby_enquiry_screen.dart';
import 'package:kmobile/l10n/app_localizations.dart';

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

  @override
  State<PMMainScreen> createState() => _PMMainScreenState();
}

class _PMMainScreenState extends State<PMMainScreen> {
  User? _selectedAccount;
  List<User> _filteredUsers = [];
  String? _selectedScheme;

  List<String> _getSchemes(AppLocalizations l10n) => [
    l10n.pmjjbyFull,
    l10n.pmsbyFull,
  ];

  @override
  void initState() {
    super.initState();
    _filteredUsers = widget.users
        .where((user) => ['SA', 'SB', 'CA', 'CC'].contains(user.accountType))
        .toList();
    // Pre-fill the account number if possible
    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;
      }
    }
  }

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

  Future<void> _handleCreate() async {
    final l10n = AppLocalizations.of(context);
    if (_selectedAccount == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.pleaseSelectAccountNumber)),
      );
      return;
    }

    if (_selectedScheme == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.pleaseSelectSchemeFirst)),
      );
      return;
    }

    final String schemeCode = (_selectedScheme == l10n.pmjjbyFull) ? '02' : '01';

    // Show loading
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const CircularProgressIndicator(),
            const SizedBox(width: 16),
            Text(l10n.fetchingDetails),
          ],
        ),
        duration: const Duration(seconds: 2),
      ),
    );

    try {
      final response = await getIt<YojnaService>().fetchpmydetails(
        scheme: schemeCode,
        action: 'C',
        accountno: _selectedAccount!.accountNo!,
      );

      if (mounted) {
        Map<String, dynamic>? data;
        if (response is Map<String, dynamic>) {
          data = response;
        } else if (response is List && response.isNotEmpty && response[0] is Map<String, dynamic>) {
          data = response[0] as Map<String, dynamic>;
        }

        if (data != null && data.isNotEmpty) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                if (_selectedScheme == l10n.pmjjbyFull) {
                  return PMJJBYScreen(initialData: data!);
                } else {
                  return PMSBYScreen(initialData: data!);
                }
              },
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(l10n.failedToFetchDetails)),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(l10n.genericError(e.toString()))),
        );
      }
    }
  }

  void _handleEnquiry() {
    final l10n = AppLocalizations.of(context);
    if (_selectedAccount == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.pleaseSelectAccountNumber)),
      );
      return;
    }

    if (_selectedScheme == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.pleaseSelectSchemeFirst)),
      );
      return;
    }

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          if (_selectedScheme == l10n.pmjjbyFull) {
            return PMJJBYEnquiryScreen(cifNumber: _selectedAccount!.cifNumber);
          } else {
            return PMSBYEnquiryScreen(cifNumber: _selectedAccount!.cifNumber);
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    final schemes = _getSchemes(l10n);
    
    // Ensure _selectedScheme is valid if it was set in a different language
    if (_selectedScheme != null && !schemes.contains(_selectedScheme)) {
       // Try to find the corresponding scheme in the new language
       // This is a bit tricky, but since we only have two:
       // If it doesn't match, it might be from the other language.
       // For simplicity, we can just reset it or try to guess.
       // Better to use non-localized values for the state, but let's just reset for now if it doesn't match
       _selectedScheme = null;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.pradhanMantriYojana),
        centerTitle: false,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  l10n.pmjjbyPmsbyDescription,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ),
            ),
            const SizedBox(height: 16),
            Card(
              elevation: 2,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    DropdownButtonFormField<User>(
                      value: _selectedAccount,
                      decoration: InputDecoration(
                        labelText: l10n.accountNumber,
                        border: const OutlineInputBorder(),
                        contentPadding: const EdgeInsets.symmetric(
                            vertical: 20, horizontal: 12),
                      ),
                      items: _filteredUsers.map((user) {
                        return DropdownMenuItem<User>(
                          value: user,
                          child: Text(user.accountNo.toString()),
                        );
                      }).toList(),
                      onChanged: (User? newUser) {
                        setState(() {
                          _selectedAccount = newUser;
                        });
                      },
                      validator: (value) {
                        if (value == null) {
                          return l10n.accountNumberRequired;
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    DropdownButtonFormField<String>(
                      value: _selectedScheme,
                      isExpanded: true,
                      isDense: false,
                      itemHeight: null,
                      decoration: InputDecoration(
                        labelText: l10n.selectScheme,
                        border: const OutlineInputBorder(),
                        contentPadding:
                            const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
                      ),
                       selectedItemBuilder: (BuildContext context) {  
   return schemes.map((String scheme) {        
     return Container(                          
       alignment: Alignment.centerLeft,         
       child: Text(                             
         scheme,                                
         style: const TextStyle(fontSize: 14),  
         softWrap: true,                        
         maxLines: 2,                           
         overflow: TextOverflow.visible,        
       ),                                       
     );                                         
   }).toList();                                 
 },                                             
                      items: schemes.map((String scheme) {
                        return DropdownMenuItem<String>(
                          value: scheme,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(vertical: 12.0),
                            child: Text(
                              scheme,
                              style: const TextStyle(fontSize: 15),

                              softWrap: true,
                            ),
                          ),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          _selectedScheme = newValue;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _handleCreate,
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          Theme.of(context).colorScheme.primaryContainer,
                      foregroundColor:
                          Theme.of(context).colorScheme.onPrimaryContainer,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      elevation: 4,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: Text(
                      l10n.create,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _handleEnquiry,
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          Theme.of(context).colorScheme.primaryContainer,
                      foregroundColor:
                          Theme.of(context).colorScheme.onPrimaryContainer,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      elevation: 4,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: Text(
                      l10n.enquiry,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

