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

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

class _emp_detailsCreateEntityScreenState extends State<emp_detailsCreateEntityScreen> {

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


  final TextEditingController numberaController = TextEditingController();


  final TextEditingController phone_numberController = TextEditingController();


  final TextEditingController paragraph_fieldController = TextEditingController();



  bool _passwordVisiblepassword_field = false;
  bool _isPasswordValidpassword_field = true;
  bool _doPasswordsMatchpassword_field = true;

  String _passwordpassword_field = ''; // To store the first password

  void _validatePasswordpassword_field(String password) {
    setState(() {
      _isPasswordValidpassword_field = password.isNotEmpty;
      _passwordpassword_field = password; // Store the password for later comparison
      _doPasswordsMatchpassword_field = true; // Reset match flag on new input
    });
  }

  void _validateConfirmPasswordpassword_field(String confirmPassword) {
    setState(() {
      _doPasswordsMatchpassword_field = confirmPassword == _passwordpassword_field;
    });
  }

  final TextEditingController textarea_fieldController = TextEditingController();


TextEditingController date_field = TextEditingController(); 

 DateTime selectedDatedate_field = DateTime.now();
  Future<void> _selectDatedate_field(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDatedate_field,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != selectedDatedate_field) {
      setState(() {
        selectedDatedate_field = picked;
      });
    }
  }


  final TextEditingController datetime_fieldController = TextEditingController();


  bool _isemail_fieldEmailValid = true;
  void _validateemail_fieldEmail(String email) {
    setState(() {
      _isemail_fieldEmailValid = RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$').hasMatch(email);
    });
  }


bool _isSwitchedtoggle_switch = false;
bool toggle_switch = false;

void _toggleSwitchtoggle_switch(bool value) {
  setState(() {
    _isSwitchedtoggle_switch = value;
  });
}

  bool _isUrlValidurl_field = true;
  void _validateUrlurl_field(String url) {
    setState(() {
      _isUrlValidurl_field = Uri.parse(url).isAbsolute;
    });
  }


  final TextEditingController decimal_fieldController = TextEditingController();


  final TextEditingController percentage_fieldController = TextEditingController();


late String recaptchacaptcha;
  TextEditingController _recaptchaController = TextEditingController();
  final GlobalKey<ScaffoldMessengerState> _recaptchascaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptchaCaptcha() {
    final random = Random();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    recaptchacaptcha = String.fromCharCodes(Iterable.generate(
        6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

  void verifyrecaptchaCaptcha() {
    print("Verifying captcha");
    if (_recaptchaController.text.isEmpty) {
      print("recaptcha is empty");
      recaptchaSnackbar('Please enter CAPTCHA', success: false);
    } else if (_recaptchaController.text != recaptchacaptcha) {
      print("captcha is not matching");
      recaptchaSnackbar('CAPTCHA verification failed', success: false);
    } else {
      print("captcha is verified");
      recaptchaSnackbar('CAPTCHA Verified', success: true);
      // Navigate to another screen after verification
      // Example navigation to a new screen
     // Navigator.push(
       // context,
       // MaterialPageRoute(builder: (context) => NextScreen()),
    //  );
    }
  }

  void recaptchaSnackbar(String message, {required bool success}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: success ? Colors.green : Colors.red,
      ),
    );
  }





 

  bool qr_codecBox = false;
 

 

  bool bar_codecBox = false;
 


  List<Map<String, dynamic>> selectedfileupload_test = [];

  Future<void> _pickfileupload_test(Map<String, dynamic> newFile, StateSetter setState) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      setState(() {
        newFile['fileBytes'] = result.files.first.bytes;
        newFile['fileFileName'] = result.files.first.name;
      });
     ToastMessageUtil.showToast(
            message: "File Uploaded",
            toastType: ToastType.success);
    } else {
      print("No files selected");
    }
  }

  Widget _fileupload_testbuildUploadRow(Map<String, dynamic> newFile) {
    return StatefulBuilder(builder: (context, setState) {
      String? selectedFileName = newFile['fileFileName'];
      return Card(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        child: ListTile(
          leading: Icon(Icons.file_copy, color: Colors.blueAccent),
          title: Text(selectedFileName ?? 'No file selected', style: TextStyle(color: Colors.grey[700])),
          trailing: ElevatedButton(
            onPressed: () => _pickfileupload_test(newFile, setState),
            child: const Text('Select File'),
          ),
        ),
      );
    });
  }

  void _addfileupload_testUploadRow() {
    Map<String, dynamic> newFile = {};
    setState(() {
      selectedfileupload_test.add(newFile);
    });
  }

  void _removefileupload_testUploadRow(int index) {
    setState(() {
      selectedfileupload_test.removeAt(index);
    });
  }

  Future<void> _uploadfileupload_test(int entityId) async {
  // Check if selectedfileupload_test is null or empty
  if (selectedfileupload_test == null || selectedfileupload_test.isEmpty) {
    print("No files selected for upload.");
    return;
  }

  final provider = Provider.of<Emp_detailsViewModelScreen>(context, listen: false);

  for (var selectedfile in selectedfileupload_test) {
    // Ensure selectedfile is not null and has valid data
    if (selectedfile == null ||
        selectedfile['fileFileName'] == null ||
        selectedfile['fileBytes'] == null) {
      print("Skipping a file due to missing data: $selectedfile");
      continue; // Skip this iteration
    }

    try {
      await provider.uploadfileupload_test(
        entityId.toString(),
        'Emp_details',
        selectedfile['fileFileName'],
        selectedfile['fileBytes'],
      );
      print("File uploaded successfully: ${selectedfile['fileFileName']}");
    } catch (e) {
      print("Failed to upload file: ${selectedfile['fileFileName']} - Error: $e");
    }
  }
}


  List<Map<String, dynamic>> selectedimageupload_test = [];

  Future<void> _showimageupload_testImage(Map<String, dynamic> newImage, StateSetter setState) async {
    final ImagePicker picker = ImagePicker();

    // Show a dialog to choose the source
    final ImageSource? source = await showDialog<ImageSource>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('Select Image Source'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.of(context).pop(ImageSource.camera),
            child: const Text('Camera'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(ImageSource.gallery),
            child: const Text('Gallery'),
          ),
        ],
      ),
    );

    if (source != null) {
      final XFile? pickedImage = await picker.pickImage(source: source);

      if (pickedImage != null) {
        Uint8List imageBytes = await pickedImage.readAsBytes();
        setState(() {
          newImage['imageBytes'] = imageBytes;
          newImage['imageFileName'] = pickedImage.name;
        });
      ToastMessageUtil.showToast(
            message: "File Uploaded",
            toastType: ToastType.success);
      } else {
        print("No image selected");
      }
    }
  }

  Widget _buildUploadRowimageupload_test(Map<String, dynamic> newImage) {
    return StatefulBuilder(builder: (context, setState) {
      String? selectedFileName = newImage['imageFileName'];
      Uint8List? imageBytes = newImage['imageBytes'];
      return Card(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        child: ListTile(
          leading: imageBytes != null
              ? Image.memory(imageBytes, width: 50, height: 50, fit: BoxFit.cover)
              : Icon(Icons.image, color: Colors.blueAccent),
          title: Text(selectedFileName ?? 'No image selected', style: TextStyle(color: Colors.grey[700])),
          trailing: ElevatedButton(
            onPressed: () => _showimageupload_testImage(newImage, setState),
            child: const Text('Select Image'),
          ),
        ),
      );
    });
  }

  void _addUploadRowimageupload_test() {
    Map<String, dynamic> newImage = {};
    setState(() {
      selectedimageupload_test.add(newImage);
    });
  }

  void _removeUploadRowimageupload_test(int index) {
    setState(() {
      selectedimageupload_test.removeAt(index);
    });
  }

  Future<void> _uploadimageupload_test(int entityId) async {

 // Check if the selectedimageupload_field list is null or empty
    if (selectedimageupload_test == null ||
        selectedimageupload_test.isEmpty) {
      print("No images selected for upload.");
      return;
    }
final provider =
          Provider.of<Emp_detailsViewModelScreen>(context, listen: false);
    for (var selectedImage in selectedimageupload_test) {
 if (selectedImage == null ||
          selectedImage['imageFileName'] == null ||
          selectedImage['imageBytes'] == null) {
        print("Skipping an image due to missing data: $selectedImage");
        continue; // Skip this iteration
      }

      try {
     
      await provider.uploadimageupload_test(
                               entityId.toString(),
        'Emp_details',
        selectedImage['imageFileName'],
        selectedImage['imageBytes'],
      );
        print("Image uploaded successfully: ${selectedImage['imageFileName']}");
      } catch (e) {
        print(
            "Failed to upload image: ${selectedImage['imageFileName']} - Error: $e");
      }
    }
  }

  AudioPlayer _audioPlayeraudio_test = AudioPlayer();
  String? _filePathaudio_test;
  String? _fileNameaudio_test;
  bool _isPlayingaudio_test = false;
  Duration _durationaudio_test = Duration();
  Duration _positionaudio_test = Duration();

  Future<void> _pickAudioaudio_test() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.audio);

    if (result != null) {
      setState(() {
        _filePathaudio_test = result.files.single.path;
        _fileNameaudio_test = result.files.single.name;
      });
      await _audioPlayeraudio_test.setFilePath(_filePathaudio_test!);
      _playPauseAudioaudio_test();
    }
  }

  void _playPauseAudioaudio_test() {
    if (_isPlayingaudio_test) {
      _audioPlayeraudio_test.pause();
    } else {
      _audioPlayeraudio_test.play();
    }
    setState(() {
      _isPlayingaudio_test = !_isPlayingaudio_test;
    });
  }
  void _stopAudioaudio_test() {
    _audioPlayeraudio_test.stop();
    setState(() {
      _isPlayingaudio_test = false;
      _positionaudio_test = Duration(seconds: 0);
    });
  }

  void _seekAudioaudio_test(Duration position) {
    _audioPlayeraudio_test.seek(position);
  }

 Future<void> _uploadaudio_test(int entityId) async {

   try {
       // Check if the file path and file name are available
    if (_filePathaudio_test == null ) {
      print('No file selected for upload.');
      return;
    }
        // Read the file as bytes
        Uint8List fileBytes = await File(_filePathaudio_test!).readAsBytes();
        String fileName = _fileNameaudio_test!;
  final provider = Provider.of<Emp_detailsViewModelScreen>(context, listen: false);

           await provider.uploadaudio_test(

     
                               entityId.toString(),
                              'Emp_details',
       fileName,
          fileBytes,
        );
        print('Audio uploaded successfully');
     
    } catch (error) {
      print('Error uploading video: $error');
    }
  }

String inputValuecurrencys = '';
String outputValuecurrencys = '';

void _convertCurrency_currencys() {
  String inputText = inputValuecurrencys.replaceAll(',', ''); // Remove commas
  try {
    double parsedValue = double.parse(inputText); // Parse the value
    String formattedValue =
        parsedValue.toStringAsFixed(2); // Format to 2 decimal places
    setState(() {
      outputValuecurrencys = formattedValue;
    });
  } catch (e) {
    setState(() {
      outputValuecurrencys = "Invalid input";
    });
  }
}


 String inputDatabarcode_test = 'Hello BarCode'; // By default barcode
  TextEditingController controllerInputbarcode_test = 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';
    });
  }

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


























   generaterecaptchaCaptcha();









_audioPlayeraudio_test.durationStream.listen((Duration? d) {
    setState(() {
      _durationaudio_test = d ?? Duration.zero;
    });
  });
  

  _audioPlayeraudio_test.positionStream.listen((Duration p) {
    setState(() {
      _positionaudio_test = p;
    });
  });

  _audioPlayeraudio_test.playerStateStream.listen((PlayerState state) {
    if (state.processingState == ProcessingState.completed) {
      setState(() {
        _isPlayingaudio_test = false;
        _positionaudio_test = Duration(seconds: 0);
      });
    }
  });



  controllerInputbarcode_test.text = inputDatabarcode_test;





} 

  

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














































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

  onSaved:(value) => formData['text_field'] = value ,
  label:"Enter Text Field",
  // ValidationProperties
),

  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(
              onSaved:(value) => formData['phone_number'] = value ,
              label: "Enter Phone Number",
              keyboardType: TextInputType.number,
              inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(
                        10), // Limit input to 10 digits
            ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter Phone Number';
                }
                if (value.length != 10) {
                      return 'Phone number must be exactly 10 digits';
                    }
                    return null;
              },
            ),

ReusableTextField(
                  controller: paragraph_fieldController,

              onSaved:(value) => formData['paragraph_field'] = value ,
              label: "Enter Paragraph Field",
              maxLines: 5,

            ),

TextFormField(
                  obscureText: !_passwordVisiblepassword_field,
                  decoration: InputDecoration(
                    labelText: 'Password Field',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepassword_field
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepassword_field = !_passwordVisiblepassword_field;
                        });
                      },
                    ),
                    errorText:
                        _isPasswordValidpassword_field ? null : 'Please enter a password',
                    border: OutlineInputBorder(),
                  ),
                  onSaved: (value) => formData['password_field'] = value,
                  onChanged: _validatePasswordpassword_field,
                ),
                const SizedBox(height: 16),
                TextFormField(
                  obscureText: !_passwordVisiblepassword_field,
                  decoration: InputDecoration(
                    labelText: 'Confirm Password Field',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepassword_field
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepassword_field = !_passwordVisiblepassword_field;
                        });
                      },
                    ),
                    errorText:
                        _doPasswordsMatchpassword_field ? null : 'Passwords do not match',
                    border: OutlineInputBorder(),
                  ),
                  onChanged: _validateConfirmPasswordpassword_field,
                ),

ReusableTextField(
                  controller: textarea_fieldController,

  onSaved:(value) => formData['textarea_field'] = value ,
  label: "Enter Textarea Field",
  maxLines: 5,
// ValidationProperties
),


                       SizedBox(height: 16),


ReusableDatePickerField(
                label:' Date Field', controller: date_field 
,
                                      onSaved: (value) => formData['date_field'] = value,),
const SizedBox(height: 16),


ReusableTextField(
                  controller: datetime_fieldController,

  onSaved:(value) => formData['datetime_field'] = value ,
  label:"Enter Datetime Field",
  // ValidationProperties
),

  SizedBox(height: 16),



Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Email Field",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle.txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Email Field",
    errorText: _isemail_fieldEmailValid ? null : 'Please enter a valid email',

onsaved: (value) => formData['email_field'] = value,
  onChanged: (value) {
    _validateemail_fieldEmail(value);
  },                            
  margin: getMargin(top: 6))
                        ])),

 Switch(
              value: _isSwitchedtoggle_switch,
              onChanged: _toggleSwitchtoggle_switch,
              activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.red,
            ),


Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Url Field",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle.txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Url Field",
    errorText: _isUrlValidurl_field ? null : 'Please enter a valid URL',
  keyboardType: TextInputType.url,


                              onsaved: (value) => formData['url_field'] = value,
  onChanged: _validateUrlurl_field,

                              margin: getMargin(top: 6))
                        ])),
SizedBox(height: 16),

ReusableTextField(
                  controller: decimal_fieldController,

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

SizedBox(height: 16), 

ReusableTextField(
                  controller: percentage_fieldController,

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

SizedBox(height: 16), 

Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Enter the following CAPTCHA:',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    recaptchacaptcha,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                      letterSpacing: 4,
                      fontFamily: 'Roboto',
                      decoration: TextDecoration.none,
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.refresh),
                    onPressed: () {
                      setState(() {
                        generaterecaptchaCaptcha();
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 24),
            TextFormField(
              controller: _recaptchaController,
              decoration: InputDecoration(
                labelText: 'Enter CAPTCHA',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: verifyrecaptchaCaptcha,
              child: Text('Verify CAPTCHA'),
            ),
          ],
        ),
      ),



                Row(
                  children: [


 
                    Checkbox(
                      value: qr_codecBox,
                      onChanged: (newValue) {
                        setState(() {
                          qr_codecBox = newValue!;
                        });
                      },
                    ),
                    const SizedBox(width: 8),
                    Text('Qr_code'),

 

 
                    Checkbox(
                      value: bar_codecBox,
                      onChanged: (newValue) {
                        setState(() {
                          bar_codecBox = newValue!;
                        });
                      },
                    ),
                    const SizedBox(width: 8),
                    Text('Bar_code'),

 
                  ],
                ),
                SizedBox(height: 16),

 SizedBox(
                  height:  MediaQuery.of(context).size.height*0.5,
child: Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: selectedfileupload_test.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    _fileupload_testbuildUploadRow(selectedfileupload_test[index]),
                    Positioned(
                      right: 8,
                      top: 8,
                      child: IconButton(
                        icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                        onPressed: () {
                          _removefileupload_testUploadRow(index);
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Add File Upload Row'),
            onPressed: _addfileupload_testUploadRow,
            style: ElevatedButton.styleFrom(
              foregroundColor: Colors.white, backgroundColor: Colors.blueAccent,
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              textStyle: const TextStyle(fontSize: 16),
            ),
          ),
          const SizedBox(height: 16),
        
        ],
      ),
    ),),
 const SizedBox(height: 16),

 SizedBox(
                  height:  MediaQuery.of(context).size.height*0.5,
child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: selectedimageupload_test.length,
                itemBuilder: (context, index) {
                  return Stack(
                    children: [
                      _buildUploadRowimageupload_test(selectedimageupload_test[index]),
                      Positioned(
                        right: 8,
                        top: 8,
                        child: IconButton(
                          icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                          onPressed: () {
                            _removeUploadRowimageupload_test(index);
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('Add Image Upload Row'),
              onPressed: _addUploadRowimageupload_test,
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.blueAccent,
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                textStyle: const TextStyle(fontSize: 16),
              ),
            ),
            const SizedBox(height: 16),
           
          ],
        ),
      ),
    ),

  const SizedBox(height: 16),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            if (_fileNameaudio_test != null)
              Text(
                _fileNameaudio_test!,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            if (_filePathaudio_test != null)
              Slider(
                value: _positionaudio_test.inSeconds.toDouble(),
                min: 0.0,
                max: _durationaudio_test.inSeconds.toDouble(),
                onChanged: (double value) {
                  setState(() {
                    _seekAudioaudio_test(Duration(seconds: value.toInt()));
                  });
                },
              ),
            if (_filePathaudio_test != null)
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    icon: Icon(Icons.skip_previous),
                    onPressed: () {
                      final newPosition = _positionaudio_test - Duration(seconds: 10);
                      _seekAudioaudio_test(newPosition < Duration(seconds: 0) ? Duration(seconds: 0) : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(_isPlayingaudio_test ? Icons.pause : Icons.play_arrow),
                    onPressed: _playPauseAudioaudio_test,
                  ),
                  IconButton(
                    icon: Icon(Icons.skip_next),
                    onPressed: () {
                      final newPosition = _positionaudio_test + Duration(seconds: 10);
                      _seekAudioaudio_test(newPosition > _durationaudio_test ? _durationaudio_test : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.stop),
                    onPressed: _stopAudioaudio_test,
                  ),
                ],
              ),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              icon: Icon(Icons.audiotrack),
              label: Text('Pick Audio'),
              onPressed: _pickAudioaudio_test,
            ),
          ],
        ),
      ),

 TextFormField(
                        keyboardType: TextInputType.number,
                        onChanged: (text) {
                          setState(() {
                            inputValuecurrencys = text;
                          });
                        },
                        decoration: const InputDecoration(
                          labelText:
                          'Enter Currency Value (with or without commas)',
                          prefixIcon: Icon(Icons.currency_rupee),
                      border: OutlineInputBorder(),

                        ),
                        onSaved: (value) {
                          _convertCurrency_currencys();
                          formData['currencys'] = outputValuecurrencys;
                        }),
                const SizedBox(height: 16),  

 Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'Generate Barcode',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            if (inputDatabarcode_test.isNotEmpty)
              BarcodeWidget(
                barcode: Barcode.code128(), // Choose the type of barcode
                data: inputDatabarcode_test,
                width: 200,
                height: 80,
              ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputbarcode_test,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for barcode',
              ),
              onChanged: (value) {
                setState(() {
                  inputDatabarcode_test = value;
  formData['barcode_test'] = inputDatabarcode_test;
                });
              },
            ),
            const 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(); 


















formData['toggle_switch'] = toggle_switch;













 
                      formData['qr_code'] = qr_codecBox;
 

 
                      formData['bar_code'] = bar_codecBox;
 
















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
































                        await _uploadfileupload_test(createdEntity['id']);


                        await _uploadimageupload_test(createdEntity['id']);


                        await _uploadaudio_test(createdEntity['id']);










 

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














































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