// 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 '../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 '../../../../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 testmCreateEntityScreen extends StatefulWidget {
  const testmCreateEntityScreen({super.key});

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

class _testmCreateEntityScreenState extends State<testmCreateEntityScreen> {

final Map<String, dynamic> formData = {};
  final _formKey = GlobalKey<FormState>();
  final TextEditingController namemController = TextEditingController();


  String? dropdownValueselectsta;
  List<String> staticOptionsselectsta = [

 
'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<String> selectedselectmulsta = [];
  List<String> selectmulstaList = [

 
    '  q  ',
     

 
    '  b  ',
     

 
    '  c  ',
     

  ];

 Widget _buildMultiSelectDropdownselectmulsta(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>> selecdyaItems = [];
  var selectedselecdyaValue = ''; // Use nullable type  Future<void> _load

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

  TextEditingController selectdyamulController = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>>  selectdyamulkey = GlobalKey();
Future<List<String>> _loadselectdyamulItems() async {
    try {
final provider =
          Provider.of<TestmViewModelScreen>(context, listen: false);

      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;

 

        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(
            decoration: InputDecoration(
              labelText: fieldOption,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onSaved: (value) {
              if (formData['child'] == null) {
                formData['child'] = {};
              }
              formData['child'][fieldOption] = value;
            },
          ),
        ),
      ),
    );
  }

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

  Future<List<Map<String, dynamic>>> valuellfetchData() async {
    
    final resp = await apiService.getEntities();

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


  void showvaluellDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: AlertDialog(
            title: const Text('Select a record'),
            content: FutureBuilder<List<Map<String, dynamic>>>(
              future: _valuelldataFuture,
              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 List<String> columnsToShow = [

                    
 

                    'namem', 
                     

                    ];
                  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: columnsToShow
                          .map(
                            (key) => DataColumn(
                              label: Text(
                                key,
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 16),
                              ),
                            ),
                          )
                          .toList(),
                      rows: snapshot.data!.map((item) {
                        return DataRow(
                            cells: columnsToShow.map((key) {
                          return DataCell(
                            Text(
                              item[key].toString(),
                              style: const TextStyle(fontSize: 14),
                            ),
                            onTap: () {
                              setState(() {

 
                                namemController.text = item['namem'] ?? '';
 

                                // Add more fields as needed
                              });
                              Navigator.pop(context);
                            },
                          );
                        }).toList());
                      }).toList(),
                    ),
                  );
                }
              },
            ),
            actions: [
              TextButton(
                child: const Text('Close'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      },
    );
  }


  final TextEditingController fieldggController = TextEditingController();


  final TextEditingController numberaController = TextEditingController();


  final TextEditingController numberbController = TextEditingController();



  
  String calculatedaddOperator = '+';
  String calculatedaddresult = '';

  final List<String> calculatedaddoperators = ['+', '-', '*', '/'];

  void calculatecalculatedaddResult() {
    int calculation;
    switch (calculatedaddOperator) {
      case '+':
        calculation = 

 
int.parse(numberaController.text) +

  

 
int.parse(numberbController.text) +

  

0;


        break;
      case '-':
        calculation =

 
int.parse(numberaController.text) -
  

 
int.parse(numberbController.text) -
  

0;
        break;
      case '*':
        calculation =

 
int.parse(numberaController.text) *
  

 
int.parse(numberbController.text) *
  

1;
        break;
      case '/':
        if (

 
int.parse(numberaController.text)== 0 || 
  

 
int.parse(numberbController.text)== 0 || 
  



1 != 1) {
          calculatedaddresult = 'Division by zero error';
          return;
        }
        calculation = (

 
int.parse(numberaController.text) /
  

 
int.parse(numberbController.text) /
  


1).toInt();
        break;
      default:
        calculation = 0;
    }
    setState(() {
      calculatedaddresult = 'Result: $calculation';
    });
  }

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

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

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

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






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

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










    _valuelldataFuture = valuellfetchData(); // Initialize _dataFuture with the function










    _datagggdataFuture = datagggfetchData(); // Initialize _dataFuture with the function


} 

  

  @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: "Create Testm"),















 actions: [
          IconButton(
            icon: const Icon(Icons.grid_on),
            onPressed: () {
              showvaluellDialog(context);
            },
          ),
        ],











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

  onSaved:(value) => formData['namem'] = value ,
  label:"Enter Namem",
  // ValidationProperties
),

  SizedBox(height: 16),


 _buildDropdownselectsta('selectsta', staticOptionsselectsta, dropdownValueselectsta, (value) {
              setState(() {
                dropdownValueselectsta = value;
  formData['selectsta'] = dropdownValueselectsta;

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


 _buildMultiSelectDropdownselectmulsta('Select selectmulsta', selectmulstaList, selectedselectmulsta, (values) {
              setState(() {
                selectedselectmulsta = values;
                formData['selectmulsta'] = selectedselectmulsta.toString();
              });
            }),


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

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "selectdyamul",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loadselectdyamulItems(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final selectdyamulItems = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return selectdyamulItems.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selectedselectdyamulValue.contains(selection)) {
                          selectedselectdyamulValue.remove(selection);
                        } else {
                          selectedselectdyamulValue.add(selection);
                        }
                        formData['selectdyamul'] = selectedselectdyamulValue.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter selectdyamul",
                          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: selectedselectdyamulValue.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selectedselectdyamulValue.remove(value);
                      formData['selectdyamul'] = selectedselectdyamulValue.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

                FutureBuilder<List<Map<String, dynamic>>>(
                  future: _loadselectautoItems(),
                  builder: (context, 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 Autocomplete<String>(
                        optionsBuilder: (TextEditingValue textEditingValue) {
                          if (textEditingValue.text.isEmpty) {
                            return const Iterable<String>.empty();
                          } else {
                            return fieldNameItems.where((String option) {
                              return option.toLowerCase().contains(
                                  textEditingValue.text.toLowerCase());
                            });
                          }
                        },
                        onSelected: (String selection) {
                          setState(() {

 
                            selectedselectautoValue = selection;
                            selectedselectautoId = selectauto.firstWhere((element) =>
                                element['namem'] == selection)['id'];
 

                            formData['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]),
                            ),
                          );
                        },
                      );
                    } else if (snapshot.connectionState ==
                        ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    } else {
                      return Text('Loading...');
                    }
                  },
                ),
                const SizedBox(height: 16),
                Text('Selected Value: $selectedselectautoValue'),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "selectautomul",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loadselectautomulItems(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final selectautomulItems = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return selectautomulItems.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selectedselectautomulValue.contains(selection)) {
                          selectedselectautomulValue.remove(selection);
                        } else {
                          selectedselectautomulValue.add(selection);
                        }
                        formData['selectautomul'] = selectedselectautomulValue.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter selectautomul",
                          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: selectedselectautomulValue.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selectedselectautomulValue.remove(value);
                      formData['selectautomul'] = selectedselectautomulValue.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

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'),
 
		

        ],
      ),
    ),



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),

 
ReusableTextField(
  onSaved:(value) => formData['bar_code'] = value ,
  label:"Enter Bar_code",
  // ValidationProperties
),

  SizedBox(height: 16),
 

 
ReusableTextField(
  onSaved:(value) => formData['qr_code'] = value ,
  label:"Enter Qr_code",
  // ValidationProperties
),

  SizedBox(height: 16),
 

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


ReusableTextField(
                  controller: numberaController,

              onSaved:(value) => formData['numbera'] = value ,
              label: "Enter Numbera",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 

ReusableTextField(
                  controller: numberbController,

              onSaved:(value) => formData['numberb'] = value ,
              label: "Enter Numberb",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 

     
            const SizedBox(height: 8.0),
            DropdownButtonFormField<String>(
              value: calculatedaddOperator,
              items: calculatedaddoperators.map((String operator) {
                return DropdownMenuItem(
                  value: operator,
                  child: Text(operator),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  calculatedaddOperator = value!;
                  print(calculatedaddOperator.toString());
                  print("value-- $value");
                });
              },
              decoration: const InputDecoration(labelText: 'Operator'),
            ),
            const SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState?.save();  // Save the form fields

                }
                calculatecalculatedaddResult();
                setState(() {

                });
              },
              child: const Text('Calculate'),
            ),
            const SizedBox(height: 20.0),
            Text(calculatedaddresult,style: TextStyle(color: Colors.black),),



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


























                SizedBox(height: 16),

FutureBuilder<List<Map<String, dynamic>>>(
      future: _datagggdataFuture,
      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),


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