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

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

class _testkCreateEntityScreenState extends State<testkCreateEntityScreen> {

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


  final TextEditingController percentagesController = TextEditingController();


late String recaptchascaptcha;
  TextEditingController _recaptchasController = TextEditingController();
  final GlobalKey<ScaffoldMessengerState> _recaptchasscaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptchasCaptcha() {
    final random = Random();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    recaptchascaptcha = String.fromCharCodes(Iterable.generate(
        6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

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

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




  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('f'),
              value: 'f',
              groupValue: selectedradios,
              onChanged: (value) {
                setState(() {
                  selectedradios = value;
                  Navigator.pop(context, value);
                });
              },
            ),
            

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


          ],
        );
      },
    );

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


 

  bool scBox = false;
 

 

  bool rcBox = false;
 

 

  bool fcBox = false;
 


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

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

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

  void _removefileuploadxUploadRow(int index) {
    setState(() {
      selectedfileuploadx.removeAt(index);
    });
  }

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

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

  for (var selectedfile in selectedfileuploadx) {
    // 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.uploadfileuploadx(
        entityId.toString(),
        'Testk',
        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>> selectedimageuploada = [];

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

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

  void _removeUploadRowimageuploada(int index) {
    setState(() {
      selectedimageuploada.removeAt(index);
    });
  }

  Future<void> _uploadimageuploada(int entityId) async {

 // Check if the selectedimageupload_field list is null or empty
    if (selectedimageuploada == null ||
        selectedimageuploada.isEmpty) {
      print("No images selected for upload.");
      return;
    }
final provider =
          Provider.of<TestkViewModelScreen>(context, listen: false);
    for (var selectedImage in selectedimageuploada) {
 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.uploadimageuploada(
                               entityId.toString(),
        'Testk',
        selectedImage['imageFileName'],
        selectedImage['imageBytes'],
      );
        print("Image uploaded successfully: ${selectedImage['imageFileName']}");
      } catch (e) {
        print(
            "Failed to upload image: ${selectedImage['imageFileName']} - Error: $e");
      }
    }
  }

  AudioPlayer _audioPlayeraudios = AudioPlayer();
  String? _filePathaudios;
  String? _fileNameaudios;
  bool _isPlayingaudios = false;
  Duration _durationaudios = Duration();
  Duration _positionaudios = Duration();

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

    if (result != null) {
      setState(() {
        _filePathaudios = result.files.single.path;
        _fileNameaudios = result.files.single.name;
      });
      await _audioPlayeraudios.setFilePath(_filePathaudios!);
      _playPauseAudioaudios();
    }
  }

  void _playPauseAudioaudios() {
    if (_isPlayingaudios) {
      _audioPlayeraudios.pause();
    } else {
      _audioPlayeraudios.play();
    }
    setState(() {
      _isPlayingaudios = !_isPlayingaudios;
    });
  }
  void _stopAudioaudios() {
    _audioPlayeraudios.stop();
    setState(() {
      _isPlayingaudios = false;
      _positionaudios = Duration(seconds: 0);
    });
  }

  void _seekAudioaudios(Duration position) {
    _audioPlayeraudios.seek(position);
  }

 Future<void> _uploadaudios(int entityId) async {

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

           await provider.uploadaudios(

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

  VideoPlayerController? _controllervideoxx;
  final ImagePicker _pickervideoxx = ImagePicker();
  bool _isPlayingvideoxx = false;
  bool _isFullScreenvideoxx = false;
  bool _showControlsvideoxx = true;

  XFile? pickedFilevideoxx;

  Future<void> _pickVideovideoxx() async {
    pickedFilevideoxx = await _pickervideoxx.pickVideo(source: ImageSource.gallery);

    if (pickedFilevideoxx != null) {
      _controllervideoxx = VideoPlayerController.file(File(pickedFilevideoxx!.path))
        ..initialize().then((_) {
          setState(() {});
          _controllervideoxx!.play();
          _isPlayingvideoxx = true;
        });
    }
  }

  void _playPauseVideovideoxx() {
    if (_controllervideoxx != null && _controllervideoxx!.value.isInitialized) {
      setState(() {
        if (_controllervideoxx!.value.isPlaying) {
          _controllervideoxx!.pause();
          _isPlayingvideoxx = false;
        } else {
          _controllervideoxx!.play();
          _isPlayingvideoxx = true;
        }
      });
    }
  }

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

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

  void _toggleFullScreenvideoxx() {
    setState(() {
      _isFullScreenvideoxx = !_isFullScreenvideoxx;
    });
  }

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

    // Extract file path and name safely
    String filePath = pickedFilevideoxx!.path;
    String fileName = pickedFilevideoxx!.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<TestkViewModelScreen>(context, listen: false);

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

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


String inputValuecurrencyx = '';
String outputValuecurrencyx = '';

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


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

 String inputDatabarcodes = 'Hello BarCode'; // By default barcode
  TextEditingController controllerInputbarcodes = TextEditingController();

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




   generaterecaptchasCaptcha();











_audioPlayeraudios.durationStream.listen((Duration? d) {
    setState(() {
      _durationaudios = d ?? Duration.zero;
    });
  });
  

  _audioPlayeraudios.positionStream.listen((Duration p) {
    setState(() {
      _positionaudios = p;
    });
  });

  _audioPlayeraudios.playerStateStream.listen((PlayerState state) {
    if (state.processingState == ProcessingState.completed) {
      setState(() {
        _isPlayingaudios = false;
        _positionaudios = Duration(seconds: 0);
      });
    }
  });





controllerInputqrcode.text = inputDataqrcode;

  controllerInputbarcodes.text = inputDatabarcodes;

} 

  

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<TestkViewModelScreen>(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 Testk"),

























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

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

SizedBox(height: 16), 

ReusableTextField(
                  controller: percentagesController,

              onSaved:(value) => formData['percentages'] = value ,
              label: "Enter Percentages",
              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(
                    recaptchascaptcha,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                      letterSpacing: 4,
                      fontFamily: 'Roboto',
                      decoration: TextDecoration.none,
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.refresh),
                    onPressed: () {
                      setState(() {
                        generaterecaptchasCaptcha();
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 24),
            TextFormField(
              controller: _recaptchasController,
              decoration: InputDecoration(
                labelText: 'Enter CAPTCHA',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: verifyrecaptchasCaptcha,
              child: Text('Verify CAPTCHA'),
            ),
          ],
        ),
      ),



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: scBox,
                      onChanged: (newValue) {
                        setState(() {
                          scBox = newValue!;
                        });
                      },
                    ),
                    const SizedBox(width: 8),
                    Text('S'),

 

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

 

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

 
                  ],
                ),
                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: selectedfileuploadx.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    _fileuploadxbuildUploadRow(selectedfileuploadx[index]),
                    Positioned(
                      right: 8,
                      top: 8,
                      child: IconButton(
                        icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                        onPressed: () {
                          _removefileuploadxUploadRow(index);
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Add File Upload Row'),
            onPressed: _addfileuploadxUploadRow,
            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: selectedimageuploada.length,
                itemBuilder: (context, index) {
                  return Stack(
                    children: [
                      _buildUploadRowimageuploada(selectedimageuploada[index]),
                      Positioned(
                        right: 8,
                        top: 8,
                        child: IconButton(
                          icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                          onPressed: () {
                            _removeUploadRowimageuploada(index);
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('Add Image Upload Row'),
              onPressed: _addUploadRowimageuploada,
              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 (_fileNameaudios != null)
              Text(
                _fileNameaudios!,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            if (_filePathaudios != null)
              Slider(
                value: _positionaudios.inSeconds.toDouble(),
                min: 0.0,
                max: _durationaudios.inSeconds.toDouble(),
                onChanged: (double value) {
                  setState(() {
                    _seekAudioaudios(Duration(seconds: value.toInt()));
                  });
                },
              ),
            if (_filePathaudios != null)
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    icon: Icon(Icons.skip_previous),
                    onPressed: () {
                      final newPosition = _positionaudios - Duration(seconds: 10);
                      _seekAudioaudios(newPosition < Duration(seconds: 0) ? Duration(seconds: 0) : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(_isPlayingaudios ? Icons.pause : Icons.play_arrow),
                    onPressed: _playPauseAudioaudios,
                  ),
                  IconButton(
                    icon: Icon(Icons.skip_next),
                    onPressed: () {
                      final newPosition = _positionaudios + Duration(seconds: 10);
                      _seekAudioaudios(newPosition > _durationaudios ? _durationaudios : newPosition);
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.stop),
                    onPressed: _stopAudioaudios,
                  ),
                ],
              ),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              icon: Icon(Icons.audiotrack),
              label: Text('Pick Audio'),
              onPressed: _pickAudioaudios,
            ),
          ],
        ),
      ),

Column(
        children: [
          Center(
            child: _controllervideoxx == null
                ? const Text('No video selected')
                : _controllervideoxx!.value.isInitialized
                ? GestureDetector(
              onTap: () {
                setState(() {
                  _showControlsvideoxx = !_showControlsvideoxx;
                });
              },
              child: Stack(
                alignment: Alignment.center,
                children: [
                  AspectRatio(
                    aspectRatio: 16 / 9,
                    child: VideoPlayer(_controllervideoxx!),
                  ),
                  if (_showControlsvideoxx)
                    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: _skipBackwardvideoxx,
                            ),
                            IconButton(
                              icon: Icon(
                                _isPlayingvideoxx ? Icons.pause : Icons.play_arrow,
                                color: Colors.white,
                              ),
                              onPressed: _playPauseVideovideoxx,
                            ),
                            IconButton(
                              icon: const Icon(Icons.forward_10, color: Colors.white),
                              onPressed: _skipForwardvideoxx,
                            ),
                            IconButton(
                              icon: Icon(
                                _isFullScreenvideoxx ? Icons.fullscreen_exit : Icons.fullscreen,
                                color: Colors.white,
                              ),
                              onPressed: _toggleFullScreenvideoxx,
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            )
                : const CircularProgressIndicator(),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _pickVideovideoxx,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Icon(Icons.video_library),
                SizedBox(width: 8),
                Text('Pick Video'),
              ],
            ),
          ),
        ],
      ),

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

                        ),
                        onSaved: (value) {
                          _convertCurrency_currencyx();
                          formData['currencyx'] = outputValuecurrencyx;
                        }),
                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,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode = value;
                });
              },
            ),
          ],
        ),
      ),
  

 Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'Generate Barcode',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            if (inputDatabarcodes.isNotEmpty)
              BarcodeWidget(
                barcode: Barcode.code128(), // Choose the type of barcode
                data: inputDatabarcodes,
                width: 200,
                height: 80,
              ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputbarcodes,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for barcode',
              ),
              onChanged: (value) {
                setState(() {
                  inputDatabarcodes = value;
  formData['barcodes'] = inputDatabarcodes;
                });
              },
            ),
            const SizedBox(height: 16),
          
          ],
        ),

   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['s'] = scBox;
 

 
                      formData['r'] = rcBox;
 

 
                      formData['f'] = fcBox;
 
















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












                        await _uploadfileuploadx(createdEntity['id']);


                        await _uploadimageuploada(createdEntity['id']);


                        await _uploadaudios(createdEntity['id']);


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


























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