// 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 first_nameController = 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,
      ),
    );
  }




  String? dropdownValueselectsta;
  List<String> staticOptionsselectsta = [

 
'bar_code', 
 

 
'qr_code', 
 

];

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

  String? selectedradios;

  Future<void> _showradiosSelectionDialog(BuildContext context) async {
    final result = await showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: const Text('Select radios'),
          children: [
           
 
            RadioListTile<String>(
              title: const Text('bar_code'),
              value: 'bar_code',
              groupValue: selectedradios,
              onChanged: (value) {
                setState(() {
                  selectedradios = value;
                  Navigator.pop(context, value);
                });
              },
            ),
            

 
            RadioListTile<String>(
              title: const Text('qr_code'),
              value: 'qr_code',
              groupValue: selectedradios,
              onChanged: (value) {
                setState(() {
                  selectedradios = value;
                  Navigator.pop(context, value);
                });
              },
            ),
            


          ],
        );
      },
    );

    if (result != null) {
      setState(() {
        selectedradios = result;
      });
    }
  }


 

  bool qcBox = false;
 

 

  bool bcBox = false;
 


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

  Future<void> _pickfileupload_field(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_fieldbuildUploadRow(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_field(newFile, setState),
            child: const Text('Select File'),
          ),
        ),
      );
    });
  }

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

  void _removefileupload_fieldUploadRow(int index) {
    setState(() {
      selectedfileupload_field.removeAt(index);
    });
  }

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

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

  for (var selectedfile in selectedfileupload_field) {
    // 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_field(
        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_field = [];

  Future<void> _showimageupload_fieldImage(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_field(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_fieldImage(newImage, setState),
            child: const Text('Select Image'),
          ),
        ),
      );
    });
  }

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

  void _removeUploadRowimageupload_field(int index) {
    setState(() {
      selectedimageupload_field.removeAt(index);
    });
  }

  Future<void> _uploadimageupload_field(int entityId) async {

 // Check if the selectedimageupload_field list is null or empty
    if (selectedimageupload_field == null ||
        selectedimageupload_field.isEmpty) {
      print("No images selected for upload.");
      return;
    }
final provider =
          Provider.of<Emp_detailsViewModelScreen>(context, listen: false);
    for (var selectedImage in selectedimageupload_field) {
 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_field(
                               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_field = AudioPlayer();
  String? _filePathaudio_field;
  String? _fileNameaudio_field;
  bool _isPlayingaudio_field = false;
  Duration _durationaudio_field = Duration();
  Duration _positionaudio_field = Duration();

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

    if (result != null) {
      setState(() {
        _filePathaudio_field = result.files.single.path;
        _fileNameaudio_field = result.files.single.name;
      });
      await _audioPlayeraudio_field.setFilePath(_filePathaudio_field!);
      _playPauseAudioaudio_field();
    }
  }

  void _playPauseAudioaudio_field() {
    if (_isPlayingaudio_field) {
      _audioPlayeraudio_field.pause();
    } else {
      _audioPlayeraudio_field.play();
    }
    setState(() {
      _isPlayingaudio_field = !_isPlayingaudio_field;
    });
  }
  void _stopAudioaudio_field() {
    _audioPlayeraudio_field.stop();
    setState(() {
      _isPlayingaudio_field = false;
      _positionaudio_field = Duration(seconds: 0);
    });
  }

  void _seekAudioaudio_field(Duration position) {
    _audioPlayeraudio_field.seek(position);
  }

 Future<void> _uploadaudio_field(int entityId) async {

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

           await provider.uploadaudio_field(

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

  VideoPlayerController? _controllervideo_field;
  final ImagePicker _pickervideo_field = ImagePicker();
  bool _isPlayingvideo_field = false;
  bool _isFullScreenvideo_field = false;
  bool _showControlsvideo_field = true;

  XFile? pickedFilevideo_field;

  Future<void> _pickVideovideo_field() async {
    pickedFilevideo_field = await _pickervideo_field.pickVideo(source: ImageSource.gallery);

    if (pickedFilevideo_field != null) {
      _controllervideo_field = VideoPlayerController.file(File(pickedFilevideo_field!.path))
        ..initialize().then((_) {
          setState(() {});
          _controllervideo_field!.play();
          _isPlayingvideo_field = true;
        });
    }
  }

  void _playPauseVideovideo_field() {
    if (_controllervideo_field != null && _controllervideo_field!.value.isInitialized) {
      setState(() {
        if (_controllervideo_field!.value.isPlaying) {
          _controllervideo_field!.pause();
          _isPlayingvideo_field = false;
        } else {
          _controllervideo_field!.play();
          _isPlayingvideo_field = true;
        }
      });
    }
  }

  void _skipForwardvideo_field() {
    if (_controllervideo_field != null && _controllervideo_field!.value.isInitialized) {
      final position = _controllervideo_field!.value.position;
      final duration = _controllervideo_field!.value.duration;
      if (position != null && duration != null) {
        final newPosition = position + const Duration(seconds: 10);
        _controllervideo_field!.seekTo(newPosition > duration ? duration : newPosition);
      }
    }
  }

  void _skipBackwardvideo_field() {
    if (_controllervideo_field != null && _controllervideo_field!.value.isInitialized) {
      final position = _controllervideo_field!.value.position;
      if (position != null) {
        final newPosition = position - const Duration(seconds: 10);
        _controllervideo_field!.seekTo(newPosition < const Duration(seconds: 0)
            ? const Duration(seconds: 0)
            : newPosition);
      }
    }
  }

  void _toggleFullScreenvideo_field() {
    setState(() {
      _isFullScreenvideo_field = !_isFullScreenvideo_field;
    });
  }

Future<void> _uploadvideo_field(int entityId) async {
  try {
    // Check if a file is selected
    if (pickedFilevideo_field == null) {
      print('No file selected for upload.');
      return;
    }

    // Extract file path and name safely
    String filePath = pickedFilevideo_field!.path;
    String fileName = pickedFilevideo_field!.name;

    // Ensure file exists before reading
    File file = File(filePath);
    if (!await file.exists()) {
      print('File not found at path: $filePath');
      return;
    }

    // Read the file as bytes safely
    Uint8List? fileBytes;
    try {
      fileBytes = await file.readAsBytes();
    } catch (e) {
      print('Error reading file: $e');
      return;
    }

    // Ensure fileBytes is not empty
    if (fileBytes.isEmpty) {
      print('File is empty, upload aborted.');
      return;
    }

    // Get the provider instance safely
    final provider = Provider.of<Emp_detailsViewModelScreen>(context, listen: false);

    // Upload the file
    await provider.uploadvideo_field(
      entityId.toString(),
      'Emp_details',
      fileName,
      fileBytes,
    );

    print('Video uploaded successfully: $fileName');
  } catch (error) {
    print('Error uploading Video: $error');
  }
}


var survey_formanswers;

String inputValuecurrency = '';
String outputValuecurrency = '';

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


  String inputDataqrcode_field = 'Hello QR!';  // Default data for QR code generation
  TextEditingController controllerInputqrcode_field = TextEditingController();

 String inputDatabarcode_field = 'Hello BarCode'; // By default barcode
  TextEditingController controllerInputbarcode_field = 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_field.durationStream.listen((Duration? d) {
    setState(() {
      _durationaudio_field = d ?? Duration.zero;
    });
  });
  

  _audioPlayeraudio_field.positionStream.listen((Duration p) {
    setState(() {
      _positionaudio_field = p;
    });
  });

  _audioPlayeraudio_field.playerStateStream.listen((PlayerState state) {
    if (state.processingState == ProcessingState.completed) {
      setState(() {
        _isPlayingaudio_field = false;
        _positionaudio_field = Duration(seconds: 0);
      });
    }
  });







controllerInputqrcode_field.text = inputDataqrcode_field;

  controllerInputbarcode_field.text = inputDatabarcode_field;





} 

  

  @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: first_nameController,

  onSaved:(value) => formData['first_name'] = value ,
  label:"Enter First name",
  // 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'),
            ),
          ],
        ),
      ),



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

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


Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "Radios",
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colors.blueGrey[900],
              ),
            ),
            const SizedBox(height: 6),
            GestureDetector(
              onTap: () => _showradiosSelectionDialog(context),
              child: AbsorbPointer(
                child: TextFormField(
                  decoration: InputDecoration(
                    hintText: "Enter Radios",
                    border: OutlineInputBorder(),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                  ),
                  controller: TextEditingController(text: selectedradios),
                  onSaved: (value) {
                    formData['radios'] = value;
                  },
                ),
              ),
            ),
            const SizedBox(height: 16),
            
          ],
        ),
      ),

                Row(
                  children: [


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

 

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

 
                  ],
                ),
                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_field.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    _fileupload_fieldbuildUploadRow(selectedfileupload_field[index]),
                    Positioned(
                      right: 8,
                      top: 8,
                      child: IconButton(
                        icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                        onPressed: () {
                          _removefileupload_fieldUploadRow(index);
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Add File Upload Row'),
            onPressed: _addfileupload_fieldUploadRow,
            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_field.length,
                itemBuilder: (context, index) {
                  return Stack(
                    children: [
                      _buildUploadRowimageupload_field(selectedimageupload_field[index]),
                      Positioned(
                        right: 8,
                        top: 8,
                        child: IconButton(
                          icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                          onPressed: () {
                            _removeUploadRowimageupload_field(index);
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('Add Image Upload Row'),
              onPressed: _addUploadRowimageupload_field,
              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_field != null)
              Text(
                _fileNameaudio_field!,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            if (_filePathaudio_field != null)
              Slider(
                value: _positionaudio_field.inSeconds.toDouble(),
                min: 0.0,
                max: _durationaudio_field.inSeconds.toDouble(),
                onChanged: (double value) {
                  setState(() {
                    _seekAudioaudio_field(Duration(seconds: value.toInt()));
                  });
                },
              ),
            if (_filePathaudio_field != null)
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    icon: Icon(Icons.skip_previous),
                    onPressed: () {
                      final newPosition = _positionaudio_field - Duration(seconds: 10);
                      _seekAudioaudio_field(newPosition < Duration(seconds: 0) ? Duration(seconds: 0) : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(_isPlayingaudio_field ? Icons.pause : Icons.play_arrow),
                    onPressed: _playPauseAudioaudio_field,
                  ),
                  IconButton(
                    icon: Icon(Icons.skip_next),
                    onPressed: () {
                      final newPosition = _positionaudio_field + Duration(seconds: 10);
                      _seekAudioaudio_field(newPosition > _durationaudio_field ? _durationaudio_field : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.stop),
                    onPressed: _stopAudioaudio_field,
                  ),
                ],
              ),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              icon: Icon(Icons.audiotrack),
              label: Text('Pick Audio'),
              onPressed: _pickAudioaudio_field,
            ),
          ],
        ),
      ),

Column(
        children: [
          Center(
            child: _controllervideo_field == null
                ? const Text('No video selected')
                : _controllervideo_field!.value.isInitialized
                ? GestureDetector(
              onTap: () {
                setState(() {
                  _showControlsvideo_field = !_showControlsvideo_field;
                });
              },
              child: Stack(
                alignment: Alignment.center,
                children: [
                  AspectRatio(
                    aspectRatio: 16 / 9,
                    child: VideoPlayer(_controllervideo_field!),
                  ),
                  if (_showControlsvideo_field)
                    Positioned(
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: Container(
                        color: Colors.black54,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.replay_10, color: Colors.white),
                              onPressed: _skipBackwardvideo_field,
                            ),
                            IconButton(
                              icon: Icon(
                                _isPlayingvideo_field ? Icons.pause : Icons.play_arrow,
                                color: Colors.white,
                              ),
                              onPressed: _playPauseVideovideo_field,
                            ),
                            IconButton(
                              icon: const Icon(Icons.forward_10, color: Colors.white),
                              onPressed: _skipForwardvideo_field,
                            ),
                            IconButton(
                              icon: Icon(
                                _isFullScreenvideo_field ? Icons.fullscreen_exit : Icons.fullscreen,
                                color: Colors.white,
                              ),
                              onPressed: _toggleFullScreenvideo_field,
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            )
                : const CircularProgressIndicator(),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _pickVideovideo_field,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Icon(Icons.video_library),
                SizedBox(width: 8),
                Text('Pick Video'),
              ],
            ),
          ),
        ],
      ),

  ElevatedButton(
                    onPressed: () async {
                     // survey_formanswers = await Navigator.push(
                     //   context,
                       // MaterialPageRoute(
                         // builder: (context) => survey_form_form_screen(),
                       // ),
                     // );
                    },
                    child: const Text('${survey_form}')),

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

                        ),
                        onSaved: (value) {
                          _convertCurrency_currency();
                          formData['currency'] = outputValuecurrency;
                        }),
                const SizedBox(height: 16),  

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Generate QR Code',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            QrImageView(
              data: inputDataqrcode_field,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode_field,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode_field = value;
                });
              },
            ),
          ],
        ),
      ),
  

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

 
                      formData['b'] = bcBox;
 






















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




































                        await _uploadfileupload_field(createdEntity['id']);


                        await _uploadimageupload_field(createdEntity['id']);


                        await _uploadaudio_field(createdEntity['id']);


                        await _uploadvideo_field(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();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      }
                    }
                  },
                ),
























































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