// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Testm_viewModel/Testm_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 testmUpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  testmUpdateEntityScreen({required this.entity});

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

class _testmUpdateEntityScreenState extends State<testmUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();




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

 
    'k',

 

 
    'm',

 

 
    'n',

 

  ];

Widget _buildDropdownselectsta(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> selectedselectmulsta = [];
  List<String> selectmulstaList = [
    
 
    'q',
     

 
    'b',
     

 
    'c',
     

  ];

Widget _buildDropdownselectmulsta(
  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['selectmulsta'] = value;
      },
    ),
  );
}


List<Map<String, dynamic>> selecdyaItems = [];
  var selectedselecdyaValue;

List<String> selectdyamulItems = [];
 List<String> selectedselectdyamulValue = [];  

  TextEditingController selectdyamulController = TextEditingController();

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

Future<List<String>> _loadselectdyamulItems() async {
final provider =
          Provider.of<TestmViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getselectdyamul();
      print('selectdyamul data is : $selectTdata');

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

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

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

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


 List<Map<String, dynamic>> selectautoItems = [];
  int? selectedselectautoId; // to store selected state id

  String selectedselectautoValue = ''; // Use nullable type  Future<void> _load

  TextEditingController selectautoController = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> selectautokey = GlobalKey();
 Future<List<Map<String, dynamic>>> _loadselectautoItems() async {
final provider =
          Provider.of<TestmViewModelScreen>(context, listen: false);

    try {
      final selectTdata = await provider.getselectauto();
      print('selectauto data is : $selectTdata');

      if (selectTdata != null && selectTdata.isNotEmpty) {
      selectautoItems = selectTdata;

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

List<String> selectautomulItems = [];
 List<String> selectedselectautomulValue = [];  

  TextEditingController selectautomulController = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> selectautomulkey = GlobalKey();
Future<List<String>> _loadselectautomulItems() async {
final provider =
          Provider.of<TestmViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getselectautomul();
      print('selectautomul data is : $selectTdata');

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

 
        selectTdata.forEach((element) {
if (element['namem'] != null)
          datareturned.add(element['namem']);
        });
 

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

Widget buildFormField(String fieldOption) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: TextFormField(
              initialValue: widget.entity['child'] != null &&
                      widget.entity['child'][fieldOption] != null
                  ? widget.entity['child'][fieldOption]
                  : '',
              decoration: InputDecoration(
                labelText: fieldOption,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
onSaved: (value) {
              if (widget.entity['child'] == null) {
                widget.entity['child'] = {};
              }
              widget.entity['child'][fieldOption] = value;
            },
            ),
          ),
        ),
        );
  }


 












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


  selectedselectsta = widget.entity['selectsta'] ?? selectstaList[0] ; // Initialize with the default value

  print(json.decode(widget.entity['selectmulsta'])['selectmulsta'].toString());
							 selectedselectmulsta= json.decode(widget.entity['selectmulsta'])['selectmulsta'];
                   print('selected selectmulstais ... $selectedselectmulsta');

    provider.getselecdya().then((value) {
      setState(() {
        selecdyaItems = value; // ✅ Update list only when data is fetched
          selectedselecdyaValue = widget.entity['selecdya'] ?? null;

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

      });

      print('Updated selecdyaItems: $selecdyaItems');
        print('Selected Value: $selectedselecdyaValue');

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

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

   selectdyamulString = selectdyamulString.substring(0, selectdyamulString.length);
selectedselectdyamulValue = selectdyamulString.split(', ');
}

selectedselectautoValue = widget.entity['selectautoname']?? 'no data' ;

 String? selectautomulString = widget.entity['selectautomul'];

if (selectautomulString != null) {
    selectautomulString = selectautomulString.substring(0, selectautomulString.length );
selectedselectautomulValue = selectautomulString.split(', ');
}



  











}

 
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<TestmViewModelScreen>(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 Testm"),        actions: [




























        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 
                        ReusableTextField(
                           
                            label: "Please Enter Namem",
                            initialValue: widget.entity['namem'] ?? '',

   // ValidationProperties
                            onSaved: (value) => widget.entity['namem'] = value,
),
                    
                          SizedBox(height: 16),




 _buildDropdownselectsta(
             'selectsta',
              selectstaList,
              selectedselectsta,
              (value) {
                setState(() {
                 selectedselectsta = value;
                  widget.entity['selectsta'] = value; // Save selected value to entity
                });
              },
            ),


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


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

 

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

 


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

FutureBuilder<List<String>>(
  future: _loadselectdyamulItems(),
  builder: (context, AsyncSnapshot<List<String>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      final selectdyamulItems = 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(selectdyamulItems);
                matches.retainWhere((s) =>
                    s.toLowerCase().contains(textEditingValue.text.toLowerCase()));
                return matches;
              }
            },
            onSelected: (String selection) {
              setState(() {
                if (selectedselectdyamulValue.contains(selection)) {
                  selectedselectdyamulValue.remove(selection);
                } else {
                  selectedselectdyamulValue.add(selection);
                }
                widget.entity['selectdyamul'] = selectedselectdyamulValue.join(',');
              });
            },
          ),
          SizedBox(height: 16),
          Text(selectedselectdyamulValue.join(',')),
        ],
      );
    } else {
      return Center(child: CircularProgressIndicator());
    }
  },
),


                FutureBuilder<List<Map<String, dynamic>>>(
                  future: _loadselectautoItems(),
                  builder: (context,
                      AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      if (snapshot.hasError) {
                        return Text('Error: ${snapshot.error}');
                      }

                      final selectauto = snapshot.data ?? [];
                      final fieldNameItems = selectauto

 
                          .map((e) => e['name'])
 

                          .where((name) => name != null)
                          .cast<String>()
                          .toList();

                      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(fieldNameItems);
                                matches.retainWhere((s) => s
                                    .toLowerCase()
                                    .contains(
                                        textEditingValue.text.toLowerCase()));
                                return matches;
                              }
                            },
                            onSelected: (String selection) {
                              setState(() {
                                selectedselectautoValue = selection;

                                selectedselectautoId = selectauto.firstWhere(
                                    (element) =>

 
                                        element['namem'] == selection)['id'];
 

                                widget.entity['selectauto'] =
                                    selectedselectautoId;
                              });
                            },
                            fieldViewBuilder: (BuildContext context,
                                TextEditingController textEditingController,
                                FocusNode focusNode,
                                VoidCallback onFieldSubmitted) {
                              return TextFormField(
                                controller: textEditingController,
                                focusNode: focusNode,
                                decoration: InputDecoration(
                                  contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 16.0),
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8.0),
                                    borderSide: BorderSide(
                                        color: Colors.deepPurple, width: 2),
                                  ),
                                  enabledBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8.0),
                                    borderSide: BorderSide(
                                        color: Colors.deepPurple, width: 2),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8.0),
                                    borderSide: BorderSide(
                                        color: Colors.deepPurpleAccent,
                                        width: 2),
                                  ),
                                  hintText: 'Select selectauto',
                                  hintStyle: TextStyle(color: Colors.grey[600]),
                                ),
                              );
                            },
                          ),
                          SizedBox(height: 16),
                          Text(
                              'Selected Value: ${selectedselectautoValue.isNotEmpty ? selectedselectautoValue : "None"}'),
                        ],
                      );
                    } else {
                      return Center(child: CircularProgressIndicator());
                    }
                  },
                ),

FutureBuilder<List<String>>(
  future: _loadselectautomulItems(),
  builder: (context, AsyncSnapshot<List<String>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      final selectautomulItems = 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(selectautomulItems);
                matches.retainWhere((s) =>
                    s.toLowerCase().contains(textEditingValue.text.toLowerCase()));
                return matches;
              }
            },
            onSelected: (String selection) {
              setState(() {
                if (selectedselectautomulValue.contains(selection)) {
                  selectedselectautomulValue.remove(selection);
                } else {
                  selectedselectautomulValue.add(selection);
                }
                widget.entity['selectautomul'] = selectedselectautomulValue.join(',');
              });
            },
          ),
          SizedBox(height: 16),
          Text(selectedselectautomulValue.join(',')),
        ],
      );
    } else {
      return Center(child: CircularProgressIndicator());
    }
  },
),


Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            height: 20,
            child: Text(
              'Child',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          const SizedBox(height: 16), // Add space between elements


 
          buildFormField('namemmm'),
 
		
        ],
      ),
    ),

  Padding(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      

                      ElevatedButton(
                        onPressed: () {
                          // Save changes logic here
                          

                          Navigator.pop(context);
                          // Implement API call to update data
                        },
                        child: Text('Save'),
                      ),
                    ],
                  ),
                ),

Container(
  padding: EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    color: Colors.grey[200],
    borderRadius: BorderRadius.circular(8.0),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.2),
        spreadRadius: 2,
        blurRadius: 4,
        offset: Offset(0, 2),
      ),
    ],
  ),
  child: Column(
    children: [
      Text(
        "Fieldgg",
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 16),
     
      
 
      SizedBox(height: 16),
      TextFormField(
        initialValue: widget.entity['bar_code'],
        decoration: InputDecoration(
          labelText: 'fieldgg bar_code',
        ),
        onChanged: (value) {
          setState(() {
            widget.entity['bar_code'] = value;
          });
        },
      ),
       

 
      SizedBox(height: 16),
      TextFormField(
        initialValue: widget.entity['qr_code'],
        decoration: InputDecoration(
          labelText: 'fieldgg qr_code',
        ),
        onChanged: (value) {
          setState(() {
            widget.entity['qr_code'] = value;
          });
        },
      ),
       

      SizedBox(height: 16),
    ],
  ),
),
const SizedBox(height: 16),



 ReusableTextField(
              initialValue: widget.entity['numbera'].toString(),
              onSaved: (value) => widget.entity['numbera']= value,
              label: "Enter Numbera",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),

 ReusableTextField(
              initialValue: widget.entity['numberb'].toString(),
              onSaved: (value) => widget.entity['numberb']= value,
              label: "Enter Numberb",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),





 
          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 Testm: $e'),
                              actions: [
                                TextButton(
                                  child: const Text('OK'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
 },
                                  ),
                                ],
                              );
                            },
                          );
                        }
                      }
                    },
                  ),
                ],
              ),
            ),
          ),
       ),
       );
  }
}