// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Adv3_viewModel/Adv3_view_model_screen.dart';
import '../../../../utils/image_constant.dart';
import '../../../../utils/size_utils.dart';
import '../../../../theme/app_style.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:intl/intl.dart';

import 'dart:math';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
import 'package:flutter/services.dart';
class adv3UpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  adv3UpdateEntityScreen({required this.entity});

  @override
  _adv3UpdateEntityScreenState createState() => _adv3UpdateEntityScreenState();
}

class _adv3UpdateEntityScreenState extends State<adv3UpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();








  var selectedcountry; // Initialize with the default value \n);
  List<String> countryList = [

 
    'bharat',

 

 
    'nepal',

 

  ];

Widget _buildDropdowncountry(String label, List<String> options, String? value, void Function(String?) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: DropdownButtonFormField<String>(
        decoration: InputDecoration(labelText: label,
          border: OutlineInputBorder(),
),
        value: value,
        onChanged: onChanged,
        items: options.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }


  var selectedstate; // Initialize with the default value \n);
  List<String> stateList = [

 
    'maharastra',

 

 
    'bihar',

 

  ];

Widget _buildDropdownstate(String label, List<String> options, String? value, void Function(String?) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: DropdownButtonFormField<String>(
        decoration: InputDecoration(labelText: label,
          border: OutlineInputBorder(),
),
        value: value,
        onChanged: onChanged,
        items: options.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }

 List<dynamic> selectedstmlit = [];
  List<String> stmlitList = [
    
 
    'bihar',
     

 
    'sikkim',
     

  ];

Widget _buildDropdownstmlit(
  String label,
  List<String> options,
  String? selectedValue,
  String fieldName,
  void Function(String?) onChanged,
) {
  return Padding(
    padding: const EdgeInsets.symmetric(vertical: 8.0),
    child: DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(),
      ),
      value: selectedValue,
      items: options.map((String option) {
        return DropdownMenuItem<String>(
          value: option,
          child: Text(option),
        );
      }).toList(),
      onChanged: onChanged,
      onSaved: (value) {
        // Save selected value to entity or form data
      widget.entity['stmlit'] = value;
      },
    ),
  );
}


 List<dynamic> selectedstmmlt2 = [];
  List<String> stmmlt2List = [
    
 
    'p2',
     

 
    'p3',
     

 
    'ap',
     

  ];

Widget _buildDropdownstmmlt2(
  String label,
  List<String> options,
  String? selectedValue,
  String fieldName,
  void Function(String?) onChanged,
) {
  return Padding(
    padding: const EdgeInsets.symmetric(vertical: 8.0),
    child: DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(),
      ),
      value: selectedValue,
      items: options.map((String option) {
        return DropdownMenuItem<String>(
          value: option,
          child: Text(option),
        );
      }).toList(),
      onChanged: onChanged,
      onSaved: (value) {
        // Save selected value to entity or form data
      widget.entity['stmmlt2'] = value;
      },
    ),
  );
}


List<Map<String, dynamic>> dy2Items = [];
  var selecteddy2Value;

List<Map<String, dynamic>> dy1Items = [];
  var selecteddy1Value;

List<String> dymlti1Items = [];
 List<String> selecteddymlti1Value = [];  

  TextEditingController dymlti1Controller = TextEditingController();

  GlobalKey<AutoCompleteTextFieldState<String>>  dymlti1key = GlobalKey();

Future<List<String>> _loaddymlti1Items() async {
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getdymlti1();
      print('dymlti1 data is : $selectTdata');

      if (selectTdata != null && selectTdata.isNotEmpty) {
        List<String> datareturned = [];

 
        selectTdata.forEach((element) {
if (element['name'] != null)

          datareturned.add(element['name']);
        });
 

        return datareturned;
      } else {
        print('dymlti1 data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load dymlti1 items: $e');
      return [];
    }
}

List<String> dymlt2Items = [];
 List<String> selecteddymlt2Value = [];  

  TextEditingController dymlt2Controller = TextEditingController();

  GlobalKey<AutoCompleteTextFieldState<String>>  dymlt2key = GlobalKey();

Future<List<String>> _loaddymlt2Items() async {
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getdymlt2();
      print('dymlt2 data is : $selectTdata');

      if (selectTdata != null && selectTdata.isNotEmpty) {
        List<String> datareturned = [];

 
        selectTdata.forEach((element) {
if (element['name'] != null)

          datareturned.add(element['name']);
        });
 

        return datareturned;
      } else {
        print('dymlt2 data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load dymlt2 items: $e');
      return [];
    }
}


  @override
  void initState() {
    super.initState();
    final provider = Provider.of<Adv3ViewModelScreen>(context, listen: false);






  selectedcountry = widget.entity['country'] ?? countryList[0] ; // Initialize with the default value

  selectedstate = widget.entity['state'] ?? stateList[0] ; // Initialize with the default value

  print(json.decode(widget.entity['stmlit'])['stmlit'].toString());
							 selectedstmlit= json.decode(widget.entity['stmlit'])['stmlit'];
                   print('selected stmlitis ... $selectedstmlit');

  print(json.decode(widget.entity['stmmlt2'])['stmmlt2'].toString());
							 selectedstmmlt2= json.decode(widget.entity['stmmlt2'])['stmmlt2'];
                   print('selected stmmlt2is ... $selectedstmmlt2');

    provider.getdy2().then((value) {
      setState(() {
        dy2Items = value; // ✅ Update list only when data is fetched
          selecteddy2Value = widget.entity['dy2'] ?? null;

 // ✅ Fetch the stored ID and convert it to a String
        var entityValue = widget.entity['dy2'];
        if (entityValue != null) {
          selecteddy2Value = entityValue.toString();
        } else {
          selecteddy2Value = null;
        }

      });

      print('Updated dy2Items: $dy2Items');
        print('Selected Value: $selecteddy2Value');

    }).catchError((error) {
      print('Error fetching data: $error');
    });

    provider.getdy1().then((value) {
      setState(() {
        dy1Items = value; // ✅ Update list only when data is fetched
          selecteddy1Value = widget.entity['dy1'] ?? null;

 // ✅ Fetch the stored ID and convert it to a String
        var entityValue = widget.entity['dy1'];
        if (entityValue != null) {
          selecteddy1Value = entityValue.toString();
        } else {
          selecteddy1Value = null;
        }

      });

      print('Updated dy1Items: $dy1Items');
        print('Selected Value: $selecteddy1Value');

    }).catchError((error) {
      print('Error fetching data: $error');
    });

String? dymlti1String = widget.entity['dymlti1'];
if (dymlti1String != null) {

   dymlti1String = dymlti1String.substring(0, dymlti1String.length);
selecteddymlti1Value = dymlti1String.split(', ');
}

String? dymlt2String = widget.entity['dymlt2'];
if (dymlt2String != null) {

   dymlt2String = dymlt2String.substring(0, dymlt2String.length);
selecteddymlt2Value = dymlt2String.split(', ');
}

}

 
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<Adv3ViewModelScreen>(context, listen: false);
    return Scaffold(
      appBar: CustomAppBar(
          height: getVerticalSize(49),
          leadingWidth: 40,
          leading: AppbarImage(
              height: getSize(24),
              width: getSize(24),
              svgPath: ImageConstant.imgArrowleftBlueGray900,
              margin: getMargin(left: 16, top: 12, bottom: 13),
              onTap: () {
                Navigator.pop(context);
              }),
          centerTitle: true,
          title: AppbarTitle(text: "Update Adv3"),        actions: [






















        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 







 _buildDropdowncountry(
             'country',
              countryList,
              selectedcountry,
              (value) {
                setState(() {
                 selectedcountry = value;
                  widget.entity['country'] = value; // Save selected value to entity
                });
              },
            ),




 _buildDropdownstate(
             'state',
              stateList,
              selectedstate,
              (value) {
                setState(() {
                 selectedstate = value;
                  widget.entity['state'] = value; // Save selected value to entity
                });
              },
            ),


 Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDropdownstmlit(
              'Select stmlit',
              stmlitList,
              widget.entity['stmlit'], // Use entity for initial values
              'fieldName', // fieldName used to identify the value in state
              (value) {
                setState(() {
                  widget.entity['stmlit'] = value; // Save selected values to entity
                });
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // Handle save/update logic
                print('Updated values: ${widget.entity['stmlit']}');
              },
              child: Text('Save'),
            ),
          ],
        ),

 Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDropdownstmmlt2(
              'Select stmmlt2',
              stmmlt2List,
              widget.entity['stmmlt2'], // Use entity for initial values
              'fieldName', // fieldName used to identify the value in state
              (value) {
                setState(() {
                  widget.entity['stmmlt2'] = value; // Save selected values to entity
                });
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // Handle save/update logic
                print('Updated values: ${widget.entity['stmmlt2']}');
              },
              child: Text('Save'),
            ),
          ],
        ),


                ReusableDropdownField(
                  label: "Select dynmi",
                  options: dy2Items, // Your dynamic list

 

                  valueField: 'id', // ✅ API response key for ID
                  uiField: 'name', // ✅ API response key for Name

 


                  value: selecteddy2Value,
                  onChanged: (newValue) {
                    setState(() {
                      selecteddy2Value = newValue!;
                    });
                  },
                  onSaved: (newValue) {
                    widget.entity['dy2'] = selecteddy2Value?.isEmpty ?? true
                        ? 'no value'
                        : newValue!;
                  },
                ),
                const SizedBox(width: 16),


                ReusableDropdownField(
                  label: "Select dynmi",
                  options: dy1Items, // Your dynamic list

 

                  valueField: 'id', // ✅ API response key for ID
                  uiField: 'name', // ✅ API response key for Name

 


                  value: selecteddy1Value,
                  onChanged: (newValue) {
                    setState(() {
                      selecteddy1Value = newValue!;
                    });
                  },
                  onSaved: (newValue) {
                    widget.entity['dy1'] = selecteddy1Value?.isEmpty ?? true
                        ? 'no value'
                        : newValue!;
                  },
                ),
                const SizedBox(width: 16),

FutureBuilder<List<String>>(
  future: _loaddymlti1Items(),
  builder: (context, AsyncSnapshot<List<String>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      final dymlti1Items = snapshot.data ?? [];
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Autocomplete<String>(
            optionsBuilder: (TextEditingValue textEditingValue) {
              if (textEditingValue.text.isEmpty) {
                return const Iterable<String>.empty();
              } else {
                List<String> matches = <String>[];
                matches.addAll(dymlti1Items);
                matches.retainWhere((s) =>
                    s.toLowerCase().contains(textEditingValue.text.toLowerCase()));
                return matches;
              }
            },
            onSelected: (String selection) {
              setState(() {
                if (selecteddymlti1Value.contains(selection)) {
                  selecteddymlti1Value.remove(selection);
                } else {
                  selecteddymlti1Value.add(selection);
                }
                widget.entity['dymlti1'] = selecteddymlti1Value.join(',');
              });
            },
          ),
          SizedBox(height: 16),
          Text(selecteddymlti1Value.join(',')),
        ],
      );
    } else {
      return Center(child: CircularProgressIndicator());
    }
  },
),


FutureBuilder<List<String>>(
  future: _loaddymlt2Items(),
  builder: (context, AsyncSnapshot<List<String>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      final dymlt2Items = snapshot.data ?? [];
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Autocomplete<String>(
            optionsBuilder: (TextEditingValue textEditingValue) {
              if (textEditingValue.text.isEmpty) {
                return const Iterable<String>.empty();
              } else {
                List<String> matches = <String>[];
                matches.addAll(dymlt2Items);
                matches.retainWhere((s) =>
                    s.toLowerCase().contains(textEditingValue.text.toLowerCase()));
                return matches;
              }
            },
            onSelected: (String selection) {
              setState(() {
                if (selecteddymlt2Value.contains(selection)) {
                  selecteddymlt2Value.remove(selection);
                } else {
                  selecteddymlt2Value.add(selection);
                }
                widget.entity['dymlt2'] = selecteddymlt2Value.join(',');
              });
            },
          ),
          SizedBox(height: 16),
          Text(selecteddymlt2Value.join(',')),
        ],
      );
    } else {
      return Center(child: CircularProgressIndicator());
    }
  },
),


 
          CustomButton(
                  height: getVerticalSize(50),
                  text: "Update",
                  margin: getMargin(top: 24, bottom: 5),
                  onTap: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();






















       
                        try {
                        await provider.updateEntity(
                              widget.entity[
                                  'id'], // Assuming 'id' is the key in your entity map
                              widget.entity);   























                        Navigator.pop(context);
                      } catch (e) {
                        // ignore: use_build_context_synchronously
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('Error'),
                              content:
                              Text('Failed to update Adv3: $e'),
                              actions: [
                                TextButton(
                                  child: const Text('OK'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
 },
                                  ),
                                ],
                              );
                            },
                          );
                        }
                      }
                    },
                  ),
                ],
              ),
            ),
          ),
       ),
       );
  }
}