// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
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 '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart'; 
import '../../../../widgets/custom_dropdown_field.dart';
import 'dart:math';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:intl/intl.dart';
 
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart'
;import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:just_audio/just_audio.dart';
import 'package:video_player/video_player.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lottie/lottie.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'dart:io';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';






















class adv3CreateEntityScreen extends StatefulWidget {
  const adv3CreateEntityScreen({super.key});

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

class _adv3CreateEntityScreenState extends State<adv3CreateEntityScreen> {

final Map<String, dynamic> formData = {};
  final _formKey = GlobalKey<FormState>();
  late Future<List<Map<String, dynamic>>> _datagrid_fielddataFuture; // Data from fetchData

  Future<List<Map<String, dynamic>>> datagrid_fieldfetchData() async {
    
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);
    final resp = await provider.getdatagrid_fieldGrid();

      if (resp != null) {
             return resp;
      } else {
        throw Exception('Failed to load data: ');
      }
  
  }

  late Future<List<Map<String, dynamic>>> _datagrid_field2dataFuture; // Data from fetchData

  Future<List<Map<String, dynamic>>> datagrid_field2fetchData() async {
    
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);
    final resp = await provider.getdatagrid_field2Grid();

      if (resp != null) {
             return resp;
      } else {
        throw Exception('Failed to load data: ');
      }
  
  }



  String? dropdownValuecountry;
  List<String> staticOptionscountry = [

 
'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(),
      ),
    );
  }

  String? dropdownValuestate;
  List<String> staticOptionsstate = [

 
'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<String> selectedstmlit = [];
  List<String> stmlitList = [

 
    '  bihar  ',
     

 
    '  sikkim  ',
     

  ];

 Widget _buildMultiSelectDropdownstmlit(String label, List<String> options, List<String> values, void Function(List<String>) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: MultiSelectDialogField(
        items: options.map((e) => MultiSelectItem(e, e)).toList(),
        listType: MultiSelectListType.CHIP,
        initialValue: values,
        onConfirm: onChanged,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.teal),
          borderRadius: BorderRadius.circular(4),
        ),
        title: Text(label),
      ),
    );
  }

 List<String> selectedstmmlt2 = [];
  List<String> stmmlt2List = [

 
    '  p2  ',
     

 
    '  p3  ',
     

 
    '  ap  ',
     

  ];

 Widget _buildMultiSelectDropdownstmmlt2(String label, List<String> options, List<String> values, void Function(List<String>) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: MultiSelectDialogField(
        items: options.map((e) => MultiSelectItem(e, e)).toList(),
        listType: MultiSelectListType.CHIP,
        initialValue: values,
        onConfirm: onChanged,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.teal),
          borderRadius: BorderRadius.circular(4),
        ),
        title: Text(label),
      ),
    );
  }

List<Map<String, dynamic>> dy2Items = [];
  var selecteddy2Value = ''; // Use nullable type  Future<void> _load

List<Map<String, dynamic>> dy1Items = [];
  var selecteddy1Value = ''; // Use nullable type  Future<void> _load

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

  TextEditingController dymlti1Controller = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>>  dymlti1key = GlobalKey();
Future<List<String>> _loaddymlti1Items() async {
    try {
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);

      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 {
    try {
final provider =
          Provider.of<Adv3ViewModelScreen>(context, listen: false);

      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);
    _datagrid_fielddataFuture = datagrid_fieldfetchData(); // Initialize _dataFuture with the function


    _datagrid_field2dataFuture = datagrid_field2fetchData(); // Initialize _dataFuture with the function












    provider.getdy2().then((value) {
      setState(() {
        dy2Items = value; // ✅ Update list only when data is fetched
      });

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


    provider.getdy1().then((value) {
      setState(() {
        dy1Items = value; // ✅ Update list only when data is fetched
      });

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






} 

  

  @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: "Create Adv3"),
 actions: [






















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





 _buildDropdowncountry('country', staticOptionscountry, dropdownValuecountry, (value) {
              setState(() {
                dropdownValuecountry = value;
  formData['country'] = dropdownValuecountry;

              });
            }),
                const SizedBox(height: 16),


 _buildDropdownstate('state', staticOptionsstate, dropdownValuestate, (value) {
              setState(() {
                dropdownValuestate = value;
  formData['state'] = dropdownValuestate;

              });
            }),
                const SizedBox(height: 16),


 _buildMultiSelectDropdownstmlit('Select stmlit', stmlitList, selectedstmlit, (values) {
              setState(() {
                selectedstmlit = values;
                formData['stmlit'] = selectedstmlit.toString();
              });
            }),

 _buildMultiSelectDropdownstmmlt2('Select stmmlt2', stmmlt2List, selectedstmmlt2, (values) {
              setState(() {
                selectedstmmlt2 = values;
                formData['stmmlt2'] = selectedstmmlt2.toString();
              });
            }),


                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) {
                    formData['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) {
                    formData['dy1'] = selecteddy1Value?.isEmpty ?? true
                        ? 'no value'
                        : newValue!;
                  },
                ),
                const SizedBox(width: 16),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "dymlti1",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loaddymlti1Items(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final dymlti1Items = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return dymlti1Items.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selecteddymlti1Value.contains(selection)) {
                          selecteddymlti1Value.remove(selection);
                        } else {
                          selecteddymlti1Value.add(selection);
                        }
                        formData['dymlti1'] = selecteddymlti1Value.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter dymlti1",
                          filled: true,
                          fillColor: Colors.grey[200],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 20),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),
            SizedBox(height: 16),
            Text(
              'Selected Values:',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Wrap(
              spacing: 8.0,
              children: selecteddymlti1Value.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selecteddymlti1Value.remove(value);
                      formData['dymlti1'] = selecteddymlti1Value.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "dymlt2",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loaddymlt2Items(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final dymlt2Items = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return dymlt2Items.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selecteddymlt2Value.contains(selection)) {
                          selecteddymlt2Value.remove(selection);
                        } else {
                          selecteddymlt2Value.add(selection);
                        }
                        formData['dymlt2'] = selecteddymlt2Value.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter dymlt2",
                          filled: true,
                          fillColor: Colors.grey[200],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 20),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),
            SizedBox(height: 16),
            Text(
              'Selected Values:',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Wrap(
              spacing: 8.0,
              children: selecteddymlt2Value.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selecteddymlt2Value.remove(value);
                      formData['dymlt2'] = selecteddymlt2Value.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

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






















 
                      try {
                        print(formData);
  Map<String, dynamic> createdEntity =  await provider.createEntity(formData); 






















 

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

FutureBuilder<List<Map<String, dynamic>>>(
      future: _datagrid_fielddataFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('No data available..'));
        } else {
          final keys = snapshot.data!.first.keys.toList();

          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              columnSpacing: 30,
              headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue.shade100),
              dataRowColor: MaterialStateColor.resolveWith((states) => Colors.white),
              dividerThickness: 0.5,
              columns: keys.map(
                    (key) => DataColumn(
                  label: Text(
                    key,
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                ),
              )
                  .toList(),
              rows: snapshot.data!.map((item) {
                return DataRow(cells: keys.map((key) {
                  return DataCell(
                    Text(
                      item[key].toString(),
                      style: const TextStyle(fontSize: 14),
                    ),
                  );
                }).toList());
              }).toList(),
            ),
          );
        }
      },
    ),
                SizedBox(height: 16),


                SizedBox(height: 16),

FutureBuilder<List<Map<String, dynamic>>>(
      future: _datagrid_field2dataFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('No data available..'));
        } else {
          final keys = snapshot.data!.first.keys.toList();

          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              columnSpacing: 30,
              headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue.shade100),
              dataRowColor: MaterialStateColor.resolveWith((states) => Colors.white),
              dividerThickness: 0.5,
              columns: keys.map(
                    (key) => DataColumn(
                  label: Text(
                    key,
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                ),
              )
                  .toList(),
              rows: snapshot.data!.map((item) {
                return DataRow(cells: keys.map((key) {
                  return DataCell(
                    Text(
                      item[key].toString(),
                      style: const TextStyle(fontSize: 14),
                    ),
                  );
                }).toList());
              }).toList(),
            ),
          );
        }
      },
    ),
                SizedBox(height: 16),




















   ],
          ),
              ),
            ),
          ),
     );
  }
}