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

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

class _adv1CreateEntityScreenState extends State<adv1CreateEntityScreen> {

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

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

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


          ],
        );
      },
    );

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

  String? selectedidfemale;

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

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


          ],
        );
      },
    );

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


 

  bool test1cBox = false;
 



 

  bool t1cBox = 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<Adv1ViewModelScreen>(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(),
        'Adv1',
        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>> selectedfileupload_field2 = [];

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

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

  void _removefileupload_field2UploadRow(int index) {
    setState(() {
      selectedfileupload_field2.removeAt(index);
    });
  }

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

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

  for (var selectedfile in selectedfileupload_field2) {
    // 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_field2(
        entityId.toString(),
        'Adv1',
        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<Adv1ViewModelScreen>(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(),
        'Adv1',
        selectedImage['imageFileName'],
        selectedImage['imageBytes'],
      );
        print("Image uploaded successfully: ${selectedImage['imageFileName']}");
      } catch (e) {
        print(
            "Failed to upload image: ${selectedImage['imageFileName']} - Error: $e");
      }
    }
  }

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

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

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

  void _removeUploadRowimageupload_field2(int index) {
    setState(() {
      selectedimageupload_field2.removeAt(index);
    });
  }

  Future<void> _uploadimageupload_field2(int entityId) async {

 // Check if the selectedimageupload_field list is null or empty
    if (selectedimageupload_field2 == null ||
        selectedimageupload_field2.isEmpty) {
      print("No images selected for upload.");
      return;
    }
final provider =
          Provider.of<Adv1ViewModelScreen>(context, listen: false);
    for (var selectedImage in selectedimageupload_field2) {
 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_field2(
                               entityId.toString(),
        'Adv1',
        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<Adv1ViewModelScreen>(context, listen: false);

           await provider.uploadaudio_field(

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

  AudioPlayer _audioPlayeraudio_field2 = AudioPlayer();
  String? _filePathaudio_field2;
  String? _fileNameaudio_field2;
  bool _isPlayingaudio_field2 = false;
  Duration _durationaudio_field2 = Duration();
  Duration _positionaudio_field2 = Duration();

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

    if (result != null) {
      setState(() {
        _filePathaudio_field2 = result.files.single.path;
        _fileNameaudio_field2 = result.files.single.name;
      });
      await _audioPlayeraudio_field2.setFilePath(_filePathaudio_field2!);
      _playPauseAudioaudio_field2();
    }
  }

  void _playPauseAudioaudio_field2() {
    if (_isPlayingaudio_field2) {
      _audioPlayeraudio_field2.pause();
    } else {
      _audioPlayeraudio_field2.play();
    }
    setState(() {
      _isPlayingaudio_field2 = !_isPlayingaudio_field2;
    });
  }
  void _stopAudioaudio_field2() {
    _audioPlayeraudio_field2.stop();
    setState(() {
      _isPlayingaudio_field2 = false;
      _positionaudio_field2 = Duration(seconds: 0);
    });
  }

  void _seekAudioaudio_field2(Duration position) {
    _audioPlayeraudio_field2.seek(position);
  }

 Future<void> _uploadaudio_field2(int entityId) async {

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

           await provider.uploadaudio_field2(

     
                               entityId.toString(),
                              'Adv1',
       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<Adv1ViewModelScreen>(context, listen: false);

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

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


  VideoPlayerController? _controllervideo_field2;
  final ImagePicker _pickervideo_field2 = ImagePicker();
  bool _isPlayingvideo_field2 = false;
  bool _isFullScreenvideo_field2 = false;
  bool _showControlsvideo_field2 = true;

  XFile? pickedFilevideo_field2;

  Future<void> _pickVideovideo_field2() async {
    pickedFilevideo_field2 = await _pickervideo_field2.pickVideo(source: ImageSource.gallery);

    if (pickedFilevideo_field2 != null) {
      _controllervideo_field2 = VideoPlayerController.file(File(pickedFilevideo_field2!.path))
        ..initialize().then((_) {
          setState(() {});
          _controllervideo_field2!.play();
          _isPlayingvideo_field2 = true;
        });
    }
  }

  void _playPauseVideovideo_field2() {
    if (_controllervideo_field2 != null && _controllervideo_field2!.value.isInitialized) {
      setState(() {
        if (_controllervideo_field2!.value.isPlaying) {
          _controllervideo_field2!.pause();
          _isPlayingvideo_field2 = false;
        } else {
          _controllervideo_field2!.play();
          _isPlayingvideo_field2 = true;
        }
      });
    }
  }

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

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

  void _toggleFullScreenvideo_field2() {
    setState(() {
      _isFullScreenvideo_field2 = !_isFullScreenvideo_field2;
    });
  }

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

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

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

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


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
















_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);
      });
    }
  });

_audioPlayeraudio_field2.durationStream.listen((Duration? d) {
    setState(() {
      _durationaudio_field2 = d ?? Duration.zero;
    });
  });
  

  _audioPlayeraudio_field2.positionStream.listen((Duration p) {
    setState(() {
      _positionaudio_field2 = p;
    });
  });

  _audioPlayeraudio_field2.playerStateStream.listen((PlayerState state) {
    if (state.processingState == ProcessingState.completed) {
      setState(() {
        _isPlayingaudio_field2 = false;
        _positionaudio_field2 = Duration(seconds: 0);
      });
    }
  });





} 

  

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
























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

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

                Row(
                  children: [


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

 
                  ],
                ),
                SizedBox(height: 16),

                Row(
                  children: [


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

 
                  ],
                ),
                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: selectedfileupload_field2.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    _fileupload_field2buildUploadRow(selectedfileupload_field2[index]),
                    Positioned(
                      right: 8,
                      top: 8,
                      child: IconButton(
                        icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                        onPressed: () {
                          _removefileupload_field2UploadRow(index);
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Add File Upload Row'),
            onPressed: _addfileupload_field2UploadRow,
            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),

 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_field2.length,
                itemBuilder: (context, index) {
                  return Stack(
                    children: [
                      _buildUploadRowimageupload_field2(selectedimageupload_field2[index]),
                      Positioned(
                        right: 8,
                        top: 8,
                        child: IconButton(
                          icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                          onPressed: () {
                            _removeUploadRowimageupload_field2(index);
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('Add Image Upload Row'),
              onPressed: _addUploadRowimageupload_field2,
              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,
            ),
          ],
        ),
      ),

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

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

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

   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['test1'] = test1cBox;
 



 
                      formData['t1'] = t1cBox;
 


















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








                        await _uploadfileupload_field(createdEntity['id']);


                        await _uploadfileupload_field2(createdEntity['id']);


                        await _uploadimageupload_field(createdEntity['id']);


                        await _uploadimageupload_field2(createdEntity['id']);


                        await _uploadaudio_field(createdEntity['id']);


                        await _uploadaudio_field2(createdEntity['id']);


                        await _uploadvideo_field(createdEntity['id']);


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
























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