import 'package:flutter/material.dart';
import 'package:kmobile/api/services/yojna_service.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/l10n/app_localizations.dart';

class PMSBYEnquiryScreen extends StatefulWidget {
  final String? cifNumber;

  const PMSBYEnquiryScreen({
    super.key,
    required this.cifNumber,
  });

  @override
  State<PMSBYEnquiryScreen> createState() => _PMSBYEnquiryScreenState();
}

class _PMSBYEnquiryScreenState extends State<PMSBYEnquiryScreen> {
  String? _selectedFinancialYear;
  bool _isLoading = false;
  Map<String, dynamic>? _enquiryData;
  String? _errorMessage;

  final List<String> _financialYears = [
    '2021-2022',
    '2022-2023',
    '2023-2024',
    '2024-2025',
    '2025-2026',
  ];

  @override
  void initState() {
    super.initState();
    _selectedFinancialYear = null;
  }

  Future<void> _fetchEnquiryData() async {
    final l10n = AppLocalizations.of(context);
    if (_selectedFinancialYear == null || widget.cifNumber == null) return;

    setState(() {
      _isLoading = true;
      _enquiryData = null;
      _errorMessage = null;
    });

    final formattedYear = _selectedFinancialYear!.replaceAll('-', '');

    try {
      final response = await getIt<YojnaService>().enquiry(
        scheme: '01',
        action: 'E',
        financialyear: formattedYear,
        customerno: widget.cifNumber,
      );

      setState(() {
        if (response is Map<String, dynamic>) {
          if (response['status'] == 'FAILED') {
            _errorMessage = response['message'] ?? l10n.noRecordFound;
          } else {
            _enquiryData = response;
          }
        } else if (response is List && response.isNotEmpty) {
          _enquiryData = response[0] as Map<String, dynamic>;
        } else {
          _errorMessage = l10n.noDataFoundYear;
        }
      });
    } catch (e) {
      setState(() {
        _errorMessage = l10n.genericError(e.toString());
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.pmsbyDetails),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              elevation: 4,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    ListTile(
                      contentPadding: EdgeInsets.zero,
                      leading: const Icon(Icons.person, color: Colors.blue),
                      title: Text(l10n.cifNumber),
                      subtitle: Text(
                        widget.cifNumber ?? l10n.notApplicable,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    DropdownButtonFormField<String>(
                      value: _selectedFinancialYear,
                      decoration: InputDecoration(
                        labelText: l10n.selectFinancialYear,
                        border: const OutlineInputBorder(),
                        prefixIcon: const Icon(Icons.calendar_today),
                        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      ),
                      items: _financialYears.map((String year) {
                        return DropdownMenuItem<String>(
                          value: year,
                          child: Text(year),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          _selectedFinancialYear = newValue;
                        });
                        _fetchEnquiryData();
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 20),
            if (_isLoading)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(20.0),
                  child: CircularProgressIndicator(),
                ),
              )
            else if (_errorMessage != null)
              Card(
                color: Colors.red.shade50,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    _errorMessage!,
                    style: TextStyle(color: Colors.red.shade700, fontWeight: FontWeight.bold),
                    //textAlign: Center,
                  ),
                ),
              )
            else if (_enquiryData != null)
              Card(
                elevation: 4,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        l10n.schemeDetails,
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                              fontWeight: FontWeight.bold,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                      ),
                      const Divider(),
                      _buildDetailRow(l10n.customerName, _enquiryData!['customername']),
                      _buildDetailRow(l10n.policyNumber, _enquiryData!['policynumber'] ?? _enquiryData!['policyno']),
                      _buildDetailRow(l10n.accountNumber, _enquiryData!['accountno']),
                      _buildDetailRow(l10n.premiumAmount, _enquiryData!['preimiumamount'] ?? _enquiryData!['premiumamount']),
                      _buildDetailRow(l10n.nomineeName, _enquiryData!['nomineename']),
                      _buildDetailRow(l10n.date, _enquiryData!['transactiondate']),
                      _buildDetailRow(l10n.journalNo, _enquiryData!['journalno']),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, dynamic value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(fontWeight: FontWeight.w500, color: Colors.grey),
          ),
          Flexible(
            child: Text(
              value?.toString() ?? AppLocalizations.of(context).notApplicable,
              style: const TextStyle(fontWeight: FontWeight.bold),
              textAlign: TextAlign.end,
            ),
          ),
        ],
      ),
    );
  }
}
