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 PMSBYScreen extends StatefulWidget {
  final Map<String, dynamic>? initialData;
  const PMSBYScreen({super.key, this.initialData});

  @override
  State<PMSBYScreen> createState() => _PMSBYScreenState();
}

class _PMSBYScreenState extends State<PMSBYScreen> {
  final _formKey = GlobalKey<FormState>();

  // Controllers for all requested fields
  late final _aadhaarController = TextEditingController(text: widget.initialData?['aadharno']?.toString());
  late final _accountNoController = TextEditingController(text: widget.initialData?['accountno']?.toString());
  late final _balanceController = TextEditingController(text: widget.initialData?['availablebalance']?.toString());
  late final _countryController = TextEditingController(text: widget.initialData?['country']?.toString() ?? 'IN');
  late final _dobController = TextEditingController(text: widget.initialData?['customerdob']?.toString());
  late final _nameController = TextEditingController(text: widget.initialData?['customername']?.toString());
  late final _customerNoController = TextEditingController(text: widget.initialData?['customerno']?.toString());
  late final _acctOpeningDateController = TextEditingController(text: widget.initialData?['dateofacctopening']?.toString());
  late final _emailController = TextEditingController(text: widget.initialData?['emailid']?.toString());
  late final _financialYearController = TextEditingController(text: widget.initialData?['financialyear']?.toString());
  late final _genderController = TextEditingController(text: widget.initialData?['gender']?.toString());
  late final _ifscController = TextEditingController(text: widget.initialData?['ifsccode']?.toString());
  late final _marriedController = TextEditingController(text: widget.initialData?['married']?.toString());
  late final _mobileController = TextEditingController(text: widget.initialData?['mobileno']?.toString());
  late final _panController = TextEditingController(text: widget.initialData?['pan']?.toString());
  late final _pincodeController = TextEditingController(text: widget.initialData?['pincode']?.toString());
  late final _policyNumberController = TextEditingController(text: widget.initialData?['policyno']?.toString());
  late final _premiumAmountController = TextEditingController(text: widget.initialData?['premiumamount']?.toString());
  late final _stateController = TextEditingController(text: widget.initialData?['state']?.toString());
  late final _address1Controller = TextEditingController(text: widget.initialData?['address1']?.toString());
  late final _address2Controller = TextEditingController(text: widget.initialData?['address2']?.toString());
  late final _cityController = TextEditingController(text: widget.initialData?['city']?.toString());
  late final _relationWithNomineeController = TextEditingController(text: widget.initialData?['relationwithnominee']?.toString());
  late final _policyStatusController = TextEditingController(text: widget.initialData?['policystatus']?.toString());

  // Mapping options
  final Map<String, String> _healthStatusOptions = {
    '1': 'Excellent',
    '2': 'Good',
    '3': 'Bad',
  };

  final Map<String, String> _relationshipOptions = {
    '01': 'Self',
    '02': 'Wife',
    '03': 'Father',
    '04': 'Mother',
    '05': 'Son',
    '06': 'Daughter',
    '07': 'Brother',
    '08': 'Sister',
    '09': 'Father-in-law',
    '10': 'Mother-in-law',
    '11': 'Grandson',
    '12': 'Granddaughter',
    '13': 'Grandfather',
    '14': 'Grandmother',
    '15': 'Brother-in-law',
    '16': 'Sister-in-law',
    '17': 'Husband',
    '18': 'Guardian',
    '99': 'Others',
  };

  final Map<String, String> _minorOptions = {
    'Y': 'Yes',
    'N': 'No',
  };

  final Map<String, String> _ruralOptions = {
    'R': 'Rural',
    'U': 'Urban',
    'S': 'Semi-Urban',
    'M': 'Metro',
  };

  final _healthStatusController = TextEditingController();
  final _collectionChannelController = TextEditingController();
  final _nomineeNameController = TextEditingController();
  final _nomineeAddressController = TextEditingController();
  final _nomineeRelationshipController = TextEditingController();
  final _nomineeMinorController = TextEditingController();
  final _ruralCategoryController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // Initialize dropdown controllers if data exists in initialData
    if (widget.initialData != null) {
      if (widget.initialData!.containsKey('ruralcategory')) {
        _ruralCategoryController.text = widget.initialData!['ruralcategory'].toString();
      }
      if (widget.initialData!.containsKey('healthstatus')) {
        _healthStatusController.text = widget.initialData!['healthstatus'].toString();
      }
      if (widget.initialData!.containsKey('relationwithnominee')) {
        _nomineeRelationshipController.text = widget.initialData!['relationwithnominee'].toString();
      }
      if (widget.initialData!.containsKey('nomineeminor')) {
        _nomineeMinorController.text = widget.initialData!['nomineeminor'].toString();
      }
    }
  }

  @override
  void dispose() {
    _aadhaarController.dispose();
    _accountNoController.dispose();
    _balanceController.dispose();
    _countryController.dispose();
    _dobController.dispose();
    _nameController.dispose();
    _customerNoController.dispose();
    _acctOpeningDateController.dispose();
    _emailController.dispose();
    _financialYearController.dispose();
    _genderController.dispose();
    _ifscController.dispose();
    _marriedController.dispose();
    _mobileController.dispose();
    _panController.dispose();
    _pincodeController.dispose();
    _policyNumberController.dispose();
    _premiumAmountController.dispose();
    _stateController.dispose();
    _address1Controller.dispose();
    _address2Controller.dispose();
    _cityController.dispose();
    _relationWithNomineeController.dispose();
    _policyStatusController.dispose();
    _healthStatusController.dispose();
    _collectionChannelController.dispose();
    _nomineeNameController.dispose();
    _nomineeAddressController.dispose();
    _nomineeRelationshipController.dispose();
    _nomineeMinorController.dispose();
    _ruralCategoryController.dispose();
    super.dispose();
  }

  bool _isFetched(String key) {
    return widget.initialData != null && 
           widget.initialData!.containsKey(key) && 
           widget.initialData![key]?.toString().isNotEmpty == true;
  }

  Future<void> _handleRegister() async {
    final l10n = AppLocalizations.of(context);
    // Show loading spinner
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(child: CircularProgressIndicator()),
    );

    try {
      final response = await getIt<YojnaService>().secondvalidationPMSBY(
        aadharno: _aadhaarController.text,
        accountno: _accountNoController.text,
        address1: _address1Controller.text,
        address2: _address2Controller.text,
        availablebalance: _balanceController.text,
        city: _cityController.text,
        country: _countryController.text,
        customerdob: _dobController.text,
        customername: _nameController.text,
        customerno: _customerNoController.text,
        emailid: _emailController.text,
        financialyear: _financialYearController.text,
        gender: _genderController.text,
        married: _marriedController.text,
        mobileno: _mobileController.text,
        pan: _panController.text,
        pincode: _pincodeController.text,
        policyno: _policyNumberController.text,
        premiumamount: _premiumAmountController.text,
        state: _stateController.text,
        healthstatus: _healthStatusController.text,
        nomineename: _nomineeNameController.text,
        nomineeadress: _nomineeAddressController.text,
        relationwithnominee: _relationWithNomineeController.text,
        nomineeminor: _nomineeMinorController.text,
        collectionchannel: _collectionChannelController.text,
        ruralcategory: _ruralCategoryController.text,
        policystatus: _policyStatusController.text,
      );
      String x = response.toString();
      if(x.contains('RECORD ALREADY EXISTS')){
      x= l10n.recordAlreadyExists;
      }

      if (mounted) {
        // Close loading spinner
        Navigator.pop(context);
        // Show response dialog
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            title: Text(l10n.response),
            content: SingleChildScrollView(child: Text(x)),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).popUntil((route) => route.isFirst);
                },
                child: Text(l10n.close),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context); // Close loading spinner
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(l10n.genericError(e.toString()))),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.pmsbyRegistration),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildTextField(_nameController, l10n.customerName, readOnly: _isFetched('customername')),
              _buildTextField(_customerNoController, l10n.customerNo, readOnly: _isFetched('customerno')),
              _buildTextField(_accountNoController, l10n.accountNumber, keyboardType: TextInputType.number, readOnly: _isFetched('accountno')),
              _buildTextField(_balanceController, l10n.availableBalance, keyboardType: TextInputType.number, readOnly: _isFetched('availablebalance')),
              _buildTextField(_aadhaarController, l10n.aadhaarNo, keyboardType: TextInputType.number, readOnly: _isFetched('aadharno')),
              _buildTextField(_dobController, l10n.customerDobFormat, readOnly: _isFetched('customerdob')),
              _buildTextField(_genderController, l10n.gender, readOnly: _isFetched('gender')),
              _buildTextField(_marriedController, l10n.marriedYesNo, readOnly: _isFetched('married')),
              _buildTextField(_mobileController, l10n.mobileNumber, keyboardType: TextInputType.phone, readOnly: _isFetched('mobileno')),
              _buildTextField(_emailController, 'Email ID', keyboardType: TextInputType.emailAddress, readOnly: _isFetched('emailid')),
              _buildTextField(_address1Controller, l10n.address1, readOnly: _isFetched('address1')),
              _buildTextField(_address2Controller, l10n.address2, readOnly: _isFetched('address2')),
              _buildTextField(_cityController, l10n.city, readOnly: _isFetched('city')),
              _buildTextField(_panController, l10n.pan, readOnly: _isFetched('pan')),
              _buildTextField(_ifscController, l10n.ifscCode, readOnly: _isFetched('ifsccode')),
              _buildTextField(_acctOpeningDateController, l10n.dateOfAcctOpening, readOnly: _isFetched('dateofacctopening')),
              _buildTextField(_pincodeController, l10n.pincode, keyboardType: TextInputType.number, readOnly: _isFetched('pincode')),
              _buildTextField(_stateController, l10n.state, readOnly: _isFetched('state')),
              _buildTextField(_countryController, l10n.country, readOnly: _isFetched('country')),
              _buildDropdownField(_ruralCategoryController, l10n.ruralCategory, _ruralOptions, readOnly: _isFetched('ruralcategory')),
              const Divider(height: 32),
              Text(l10n.policyDetails, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              const SizedBox(height: 16),
              _buildTextField(_policyNumberController, l10n.policyNumber, readOnly: _isFetched('policyno')),
              _buildTextField(_premiumAmountController, l10n.premiumAmount, keyboardType: TextInputType.number, readOnly: _isFetched('premiumamount')),
              _buildTextField(_financialYearController, l10n.financialYear, readOnly: _isFetched('financialyear')),
              _buildTextField(_policyStatusController, l10n.policyStatus, readOnly: _isFetched('policystatus')),
              _buildDropdownField(_healthStatusController, l10n.healthStatus, _healthStatusOptions),
              _buildTextField(_collectionChannelController, l10n.collectionChannel),
              const Divider(height: 32),
              Text(l10n.nomineeDetails, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              const SizedBox(height: 16),
              _buildTextField(_nomineeNameController, l10n.nomineeName),
              _buildTextField(_nomineeAddressController, l10n.nomineeAddress),
              _buildDropdownField(_relationWithNomineeController, l10n.relationWithNominee, _relationshipOptions, readOnly: _isFetched('relationwithnominee')),
              _buildTextField(_nomineeRelationshipController, l10n.nomineeRelationship),
              _buildDropdownField(_nomineeMinorController, l10n.nomineeMinor, _minorOptions, readOnly: _isFetched('nomineeminor')),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _handleRegister,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  l10n.register,
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
              ),
              const SizedBox(height: 32),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDropdownField(
      TextEditingController controller, String label, Map<String, String> options,
      {bool readOnly = false}) {
    // Determine current value
    String? currentValue = options.containsKey(controller.text) ? controller.text : null;

    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: DropdownButtonFormField<String>(
        value: currentValue,
        onChanged: readOnly ? null : (newValue) {
          setState(() {
            controller.text = newValue ?? '';
          });
        },
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
          contentPadding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
        ),
        items: options.entries.map((entry) {
          return DropdownMenuItem<String>(
            value: entry.key,
            child: Text("${entry.key} - ${entry.value}"),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildTextField(TextEditingController controller, String label, {TextInputType keyboardType = TextInputType.text, bool readOnly = false}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: TextFormField(
        controller: controller,
        readOnly: readOnly,
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
          contentPadding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
        ),
        keyboardType: keyboardType,
      ),
    );
  }
}
