import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:doctor/common/settings.dart';
import 'package:doctor/common/zoom_image.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';

class UpdateReport extends StatefulWidget {
  var reportDetails;
  var customerId;

  UpdateReport({this.reportDetails,this.customerId});

  @override
  State<UpdateReport> createState() => _UpdateReportState();
}

class _UpdateReportState extends State<UpdateReport> {
  TextEditingController doctorNameController = TextEditingController();
  TextEditingController hospitalNameController = TextEditingController();
  TextEditingController problemController = TextEditingController();
  TextEditingController dateInput = TextEditingController();
  TextEditingController patientNameController = TextEditingController();
  TextEditingController patientAgeController = TextEditingController();
  final ImagePicker _picker = ImagePicker();
  String Url = '';
  final ImagePicker imagePicker = ImagePicker();
  List imageFileList = [];
  List imageFileListReports = [];
  List imageFileListPrescriptions = [];
  List uiFindingsImages = [];
  List uiReportsImages = [];
  List uiPrescriptionImages = [];

  List<Asset> images = <Asset>[];
  String _error = 'No Error Dectected';
  String apiMultiImages = '';
  String? prescriptionFor;
  String? gender;


  Future pickImageFromGalleryForUpdate() async {
    imageFileList = [];
    final List<XFile>? selectedImages = await imagePicker.pickMultiImage();
    AppSettings.preLoaderDialog(context);
    if (selectedImages!.isNotEmpty) {
      imageFileList.addAll(selectedImages);
    }

    var res = await AppSettings.updatePrescriptionsGallery(imageFileList,widget.reportDetails.recordId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiPrescriptionImages = jsonDecode(res)['prescription'];
    });
  }

  Future takeImageFromCameraForUpdate() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.updatePrescriptionsCamera(image,widget.reportDetails.recordId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiPrescriptionImages = jsonDecode(res)['prescription'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future pickImageFromGalleryForUpdateReports() async {
    imageFileList = [];
    final List<XFile>? selectedImages = await imagePicker.pickMultiImage();
    AppSettings.preLoaderDialog(context);
    if (selectedImages!.isNotEmpty) {
      imageFileList.addAll(selectedImages);
    }

    var res = await AppSettings.updateReportsGallery(imageFileList,widget.reportDetails.recordId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiReportsImages= jsonDecode(res)['reports'];
    });
  }

  Future takeImageFromCameraForUpdateReports() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.updateReportsCamera(image,widget.reportDetails.recordId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiReportsImages = jsonDecode(res)['reports'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future pickImageFromGalleryForUpdateFindings() async {
    imageFileList = [];
    final List<XFile>? selectedImages = await imagePicker.pickMultiImage();
    AppSettings.preLoaderDialog(context);
    if (selectedImages!.isNotEmpty) {
      imageFileList.addAll(selectedImages);
    }

    var res =
    await AppSettings.updateFindingsGallery(imageFileList, widget.reportDetails.recordId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiFindingsImages = jsonDecode(res)['findings'];
    });
  }

  Future takeImageFromCameraForUpdateFindings() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.updateFindingsCamera(image, widget.reportDetails.recordId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiFindingsImages = jsonDecode(res)['findings'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  void detials(){
    prescriptionFor=widget.reportDetails.patient_type;
    doctorNameController.text=widget.reportDetails.doctorName;
    hospitalNameController.text=widget.reportDetails.hospitalName;
    problemController.text = widget.reportDetails.problem;
    dateInput.text = widget.reportDetails.date;
    patientNameController.text =widget.reportDetails.patient_name;
    patientAgeController.text = widget.reportDetails.age;
    gender=widget.reportDetails.gender;
    uiFindingsImages=widget.reportDetails.findingsImages;
    uiReportsImages =widget.reportDetails.reportImages;
    uiPrescriptionImages =widget.reportDetails.prescriptionImages;

  }


  @override
  void initState() {


    detials();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppSettings.appBar('Update Report'),
        body: SingleChildScrollView(
          child: Container(
            child: Padding(
              padding: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: TextFormField(
                      cursorColor: greyColor,
                      controller: doctorNameController,
                      textCapitalization: TextCapitalization.words,
                      decoration: textFormFieldDecoration(
                          Icons.person, 'Enter Doctor name'),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * .02,
                  ),
                  Container(
                    child: TextFormField(
                      cursorColor: greyColor,
                      controller: hospitalNameController,
                      textCapitalization: TextCapitalization.words,
                      decoration: textFormFieldDecoration(
                          Icons.location_city_outlined, 'Enter Hospital name'),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * .02,
                  ),
                  Container(
                    child: TextFormField(
                      cursorColor: greyColor,
                      controller: problemController,
                      textCapitalization: TextCapitalization.words,
                      decoration: textFormFieldDecoration(
                          Icons.report_problem, 'Enter Problem'),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * .02,
                  ),
                  Container(
                    child: TextFormField(
                      cursorColor: greyColor,
                      controller: dateInput,
                      decoration: textFormFieldDecoration(
                          Icons.calendar_today, 'Enter Date'),
                      readOnly: true,
                      onTap: () async {
                        DateTime? pickedDate = await showDatePicker(
                          context: context,
                          initialDate: DateTime.now(),
                          firstDate: DateTime(1950),
                          lastDate: DateTime.now(),
                          builder: (BuildContext context, Widget? child) {
                            return Theme(
                              data: ThemeData.dark().copyWith(
                                colorScheme: ColorScheme.dark(
                                  primary: buttonColors,
                                  onPrimary: Colors.white,
                                  surface: buttonColors,
                                  onSurface: Colors.white,
                                ),
                                dialogBackgroundColor: primaryColor,
                              ),
                              child: child!,
                            );
                          },
                        );

                        if (pickedDate != null) {
                          print(
                              pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                          String formattedDate =
                          DateFormat('dd-MM-yyyy').format(pickedDate);
                          print(
                              formattedDate); //formatted date output using intl package =>  2021-03-16
                          setState(() {
                            dateInput.text =
                                formattedDate; //set output date to TextField value.
                          });
                        } else {}
                      },
                    ),
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: RadioListTile(
                          title: Text("For Yourself"),
                          value: "self",
                          groupValue: prescriptionFor,
                          activeColor: primaryColor,
                          onChanged: (value) {
                            setState(() {
                              prescriptionFor = value.toString();
                            });
                          },
                        ),
                      ),
                      Expanded(
                        child: RadioListTile(
                          title: Text("For Family"),
                          value: "others",
                          groupValue: prescriptionFor,
                          activeColor: primaryColor,
                          onChanged: (value) {
                            setState(() {
                              prescriptionFor = value.toString();
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  Visibility(
                    visible:
                    prescriptionFor.toString().toLowerCase() == 'others',
                    child: Container(
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: patientNameController,
                        decoration: textFormFieldDecoration(
                            Icons.person, 'Enter patient name'),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * .02,
                  ),
                  Visibility(
                    visible:
                    prescriptionFor.toString().toLowerCase() == 'others',
                    child: Container(
                      child: TextFormField(
                        cursorColor: greyColor,
                        keyboardType: TextInputType.number,
                        controller: patientAgeController,
                        decoration: textFormFieldDecoration(
                            Icons.person, 'Enter patient age'),
                      ),
                    ),
                  ),
                  Visibility(
                    visible:
                    prescriptionFor.toString().toLowerCase() == 'others',
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: RadioListTile(
                            title: Text("Male", style: TextStyle(fontSize: 10)),
                            value: "male",
                            groupValue: gender,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                gender = value.toString();
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile(
                            title: Text(
                              "Female",
                              style: TextStyle(fontSize: 10),
                            ),
                            value: "female",
                            groupValue: gender,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                gender = value.toString();
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile(
                            title:
                            Text("Others", style: TextStyle(fontSize: 10)),
                            value: "other",
                            groupValue: gender,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                gender = value.toString();
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  /*findings*/
                  Visibility(
                    visible: uiFindingsImages.length == 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdateFindings();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdateFindings();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Select Findings'),
                    ),
                  ),
                  Visibility(
                      visible: uiFindingsImages.length > 0,
                      child: Container(
                        width: double.infinity,
                        height: MediaQuery.of(context).size.height * .20,
                        child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            itemCount: uiFindingsImages.length,
                            itemBuilder: (context, index) {
                              return Column(
                                children: [
                                  Card(
                                    child: GestureDetector(
                                      onTap: () {

                                        Navigator.push(
                                            context,
                                            new MaterialPageRoute(
                                                builder: (__) => new ImageZoomPage(imageName:'Findings',imageDetails:uiFindingsImages[index]['url'])));
                                        /*gridOntap(index);*/
                                      },
                                      child: Container(
                                        width: MediaQuery.of(context).size.width *
                                            .30,
                                        height:
                                        MediaQuery.of(context).size.height *
                                            .15,
                                        decoration: BoxDecoration(
                                            shape: BoxShape.rectangle,
                                            image: DecorationImage(
                                                image: NetworkImage(
                                                    uiFindingsImages[index]['url'])
                                                as ImageProvider, // picked file
                                                fit: BoxFit.fill)),
                                        child: Stack(children: [
                                          Positioned(
                                            right: 0,
                                            child: Container(
                                              child: IconButton(
                                                iconSize: 30,
                                                icon: const Icon(
                                                  Icons.delete,
                                                  color: Colors.red,
                                                ),
                                                onPressed: () async {
                                                  showDialog(
                                                    barrierDismissible: false,
                                                    context: context,
                                                    builder: (BuildContext context) => AlertDialog(
                                                      title:
                                                      const Text('Do you want to delete image?',
                                                          style: TextStyle(
                                                            color: primaryColor,
                                                            fontSize: 20,
                                                          )),
                                                      actionsAlignment:
                                                      MainAxisAlignment.spaceBetween,
                                                      actions: [
                                                        TextButton(
                                                          onPressed: () async {
                                                            AppSettings.preLoaderDialog(context);


                                                            var payload = new Map<String, dynamic>();
                                                            payload["urlType"] = 'findings';
                                                            payload["url"] = uiFindingsImages[index]['url'];

                                                            // bool deleteStatus = await AppSettings.deleteRecordsNew(payload,widget.recordId);
                                                            try {
                                                              var res =
                                                              await AppSettings.deleteRecordsNew(
                                                                  payload,
                                                                  widget.reportDetails.recordId,widget.customerId);
                                                              print(jsonDecode(res));
                                                              Navigator.of(context,
                                                                  rootNavigator: true)
                                                                  .pop();
                                                              Navigator.of(context).pop(true);
                                                              AppSettings.longSuccessToast(
                                                                  "Image deleted Successfully");
                                                              setState(() {
                                                                uiFindingsImages = jsonDecode(res)['remainingUrls'];
                                                              });
                                                            } catch (e) {
                                                              print(e);
                                                              Navigator.of(context,
                                                                  rootNavigator: true)
                                                                  .pop();
                                                              Navigator.of(context).pop(true);
                                                              AppSettings.longFailedToast(
                                                                  "Image deletion failed");
                                                            }
                                                          },
                                                          child: const Text('Yes',
                                                              style: TextStyle(
                                                                color: primaryColor,
                                                                fontSize: 20,
                                                              )),
                                                        ),
                                                        TextButton(
                                                          onPressed: () {
                                                            Navigator.of(context).pop(true);
                                                          },
                                                          child: const Text('No',
                                                              style: TextStyle(
                                                                color: primaryColor,
                                                                fontSize: 20,
                                                              )),
                                                        ),
                                                      ],
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                          )
                                        ]),
                                      ),
                                    ),
                                  ),
                                  /*Expanded(child:IconButton(
                                    icon: const Icon(Icons.remove,color: Colors.red,),

                                    onPressed: () async{

                                    },
                                  ),)*/
                                ],
                              );
                            }),
                      )),
                  Visibility(
                    visible: uiFindingsImages.length != 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: buttonColors, // background
                        onPrimary: Colors.black, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdateFindings();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdateFindings();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Add Findings'),
                    ),
                  ),

                  /*reports*/
                  Visibility(
                    visible: uiReportsImages.length == 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdateReports();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdateReports();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Select Reports'),
                    ),
                  ),
                  Visibility(
                      visible: uiReportsImages.length > 0,
                      child: Container(
                        width: double.infinity,
                        height: MediaQuery.of(context).size.height * .20,
                        child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            itemCount: uiReportsImages.length,
                            itemBuilder: (context, index) {
                              return Column(
                                children: [
                                  Card(
                                      child: GestureDetector(
                                        onTap: () {

                                          Navigator.push(
                                              context,
                                              new MaterialPageRoute(
                                                  builder: (__) => new ImageZoomPage(imageName:'Reports',imageDetails:uiReportsImages[index]['url'])));
                                          /*gridOntap(index);*/
                                        },
                                        child: Container(
                                          width: MediaQuery.of(context).size.width *
                                              .30,
                                          height:
                                          MediaQuery.of(context).size.height *
                                              .15,
                                          decoration: BoxDecoration(
                                              shape: BoxShape.rectangle,
                                              image: DecorationImage(
                                                  image: NetworkImage(
                                                      uiReportsImages[index]['url'])
                                                  as ImageProvider, // picked file
                                                  fit: BoxFit.fill)),
                                          child: Stack(children: [
                                            Positioned(
                                              right: 0,
                                              child: Container(
                                                child: IconButton(
                                                  iconSize: 30,
                                                  icon: const Icon(
                                                    Icons.delete,
                                                    color: Colors.red,
                                                  ),
                                                  onPressed: () async {
                                                    showDialog(
                                                      barrierDismissible: false,
                                                      context: context,
                                                      builder: (BuildContext context) => AlertDialog(
                                                        title:
                                                        const Text('Do you want to delete image?',
                                                            style: TextStyle(
                                                              color: primaryColor,
                                                              fontSize: 20,
                                                            )),
                                                        actionsAlignment:
                                                        MainAxisAlignment.spaceBetween,
                                                        actions: [
                                                          TextButton(
                                                            onPressed: () async {
                                                              AppSettings.preLoaderDialog(context);

                                                              var payload = new Map<String, dynamic>();
                                                              payload["urlType"] = 'reports';
                                                              payload["url"] = uiReportsImages[index]['url'];

                                                              try {
                                                                var res =
                                                                await AppSettings.deleteRecordsNew(
                                                                    payload,
                                                                    widget.reportDetails.recordId,widget.customerId);
                                                                print(jsonDecode(res));
                                                                Navigator.of(context,
                                                                    rootNavigator: true)
                                                                    .pop();
                                                                Navigator.of(context).pop(true);
                                                                AppSettings.longSuccessToast(
                                                                    "Image deleted Successfully");
                                                                setState(() {
                                                                  uiReportsImages =
                                                                  jsonDecode(res)['remainingUrls'];
                                                                });
                                                              } catch (e) {
                                                                print(e);
                                                                Navigator.of(context,
                                                                    rootNavigator: true)
                                                                    .pop();
                                                                Navigator.of(context).pop(true);
                                                                AppSettings.longFailedToast(
                                                                    "Image deletion failed");
                                                              }
                                                            },
                                                            child: const Text('Yes',
                                                                style: TextStyle(
                                                                  color: primaryColor,
                                                                  fontSize: 20,
                                                                )),
                                                          ),
                                                          TextButton(
                                                            onPressed: () {
                                                              Navigator.of(context).pop(true);
                                                            },
                                                            child: const Text('No',
                                                                style: TextStyle(
                                                                  color: primaryColor,
                                                                  fontSize: 20,
                                                                )),
                                                          ),
                                                        ],
                                                      ),
                                                    );
                                                  },
                                                ),
                                              ),
                                            )
                                          ]),
                                        ),
                                      )
                                  ),
                                  /*Expanded(child:IconButton(
                                    icon: const Icon(Icons.remove,color: Colors.red,),

                                    onPressed: () async{

                                    },
                                  ),)*/
                                ],
                              );
                            }),
                      )),
                  Visibility(
                    visible: uiReportsImages.length != 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary:buttonColors, // background
                        onPrimary: Colors.black, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdateReports();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdateReports();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Add Reports'),
                    ),
                  ),

                  /*prescriptions*/
                  Visibility(
                    visible: uiPrescriptionImages.length == 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdate();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdate();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Select Prescriptions'),
                    ),
                  ),
                  Visibility(
                      visible: uiPrescriptionImages.length > 0,
                      child: Container(
                        width: double.infinity,
                        height: MediaQuery.of(context).size.height * .20,
                        child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            itemCount: uiPrescriptionImages.length,
                            itemBuilder: (context, index) {
                              return Column(
                                children: [
                                  Card(
                                      child: GestureDetector(
                                        onTap: () {

                                          Navigator.push(
                                              context,
                                              new MaterialPageRoute(
                                                  builder: (__) => new ImageZoomPage(imageName:'Prescriptions',imageDetails:uiPrescriptionImages[index]['url'])));
                                          /*gridOntap(index);*/
                                        },
                                        child: Container(
                                          width: MediaQuery.of(context).size.width *
                                              .30,
                                          height:
                                          MediaQuery.of(context).size.height *
                                              .15,
                                          decoration: BoxDecoration(
                                              shape: BoxShape.rectangle,
                                              image: DecorationImage(
                                                  image: NetworkImage(
                                                      uiPrescriptionImages[index]['url'])
                                                  as ImageProvider, // picked file
                                                  fit: BoxFit.fill)),
                                          child: Stack(children: [
                                            Positioned(
                                              right: 0,
                                              child: Container(
                                                child: IconButton(
                                                  iconSize: 30,
                                                  icon: const Icon(
                                                    Icons.delete,
                                                    color: Colors.red,
                                                  ),
                                                  onPressed: () async {
                                                    showDialog(
                                                      barrierDismissible: false,
                                                      context: context,
                                                      builder: (BuildContext context) => AlertDialog(
                                                        title:
                                                        const Text('Do you want to delete image?',
                                                            style: TextStyle(
                                                              color: primaryColor,
                                                              fontSize: 20,
                                                            )),
                                                        actionsAlignment:
                                                        MainAxisAlignment.spaceBetween,
                                                        actions: [
                                                          TextButton(
                                                            onPressed: () async {
                                                              AppSettings.preLoaderDialog(context);


                                                              var payload =
                                                              new Map<String, dynamic>();
                                                              payload["urlType"] = 'prescription';
                                                              payload["url"] = uiPrescriptionImages[index]['url'];

                                                              try {
                                                                var res = await AppSettings
                                                                    .deleteRecordsNew(
                                                                    payload,
                                                                    widget
                                                                        .reportDetails.recordId,widget.customerId);
                                                                print(jsonDecode(res));
                                                                Navigator.of(context,
                                                                    rootNavigator: true)
                                                                    .pop();
                                                                Navigator.of(context).pop(true);
                                                                AppSettings.longSuccessToast(
                                                                    "Image deleted Successfully");
                                                                setState(() {
                                                                  uiPrescriptionImages=
                                                                  jsonDecode(
                                                                      res)['remainingUrls'];
                                                                });
                                                              } catch (e) {
                                                                print(e);
                                                                Navigator.of(context,
                                                                    rootNavigator: true)
                                                                    .pop();
                                                                Navigator.of(context).pop(true);
                                                                AppSettings.longFailedToast(
                                                                    "Image deletion failed");
                                                              }
                                                            },
                                                            child: const Text('Yes',
                                                                style: TextStyle(
                                                                  color: primaryColor,
                                                                  fontSize: 20,
                                                                )),
                                                          ),
                                                          TextButton(
                                                            onPressed: () {
                                                              Navigator.of(context).pop(true);
                                                            },
                                                            child: const Text('No',
                                                                style: TextStyle(
                                                                  color: primaryColor,
                                                                  fontSize: 20,
                                                                )),
                                                          ),
                                                        ],
                                                      ),
                                                    );
                                                  },
                                                ),
                                              ),
                                            )
                                          ]),
                                        ),
                                      )
                                  ),
                                  /*Expanded(child:IconButton(
                                    icon: const Icon(Icons.remove,color: Colors.red,),

                                    onPressed: () async{

                                    },
                                  ),)*/
                                ],
                              );
                            }),
                      )),
                  Visibility(
                    visible: uiPrescriptionImages.length != 0,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: buttonColors, // background
                        onPrimary: Colors.black, // foreground
                      ),
                      onPressed: () async {
                        showModalBottomSheet<void>(
                            context: context,
                            builder: (BuildContext context) {
                              return SizedBox(
                                height: 200,
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      GestureDetector(
                                        child: Icon(
                                          Icons.camera_alt_outlined,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await takeImageFromCameraForUpdate();
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width *
                                            .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                          await pickImageFromGalleryForUpdate();
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: const Text('Add Prescriptions'),
                    ),
                  ),

                  /*button*/
                  Container(
                      width: double.infinity,
                      height: MediaQuery.of(context).size.height * .06,
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: buttonColors, // background
                          onPrimary: Colors.black, // foreground
                        ),
                        onPressed: () async {
                          if (doctorNameController.text != '' &&
                              problemController.text != '' &&
                              dateInput.text != '' &&
                              prescriptionFor != '') {
                            String _name = '';
                            String _age = '';
                            String? _gender = '';

                            if (prescriptionFor.toString().toLowerCase() ==
                                'others') {
                              if (patientNameController != '' &&
                                  patientAgeController.text != '' &&
                                  gender != '') {
                                _name = patientNameController.text;
                                _age = patientAgeController.text;
                                _gender = gender;
                              } else {
                                AppSettings.longFailedToast(
                                    'Please enter details');
                              }
                            } else {

                            }
                            AppSettings.preLoaderDialog(context);
                            bool isOnline =
                            await AppSettings.internetConnectivity();
                            if (isOnline) {


                              var payload = new Map<String, dynamic>();
                              payload["problem"] =
                                  problemController.text.toString();
                              payload["doctorName"] =
                                  doctorNameController.text.toString();
                              payload["hospitalName"] =
                                  hospitalNameController.text.toString();
                              payload["date"] = dateInput.text.toString();
                              payload["findings_date"] = '';
                              payload["reports_date"] = '';
                              payload["prescription_date"] = '';
                              payload["patientType"] =
                                  prescriptionFor.toString();
                              payload["others"] = {
                                "name": _name,
                                "age": int.parse(_age),
                                "gender": _gender.toString().toLowerCase()
                              };
                              payload["findings"] = uiFindingsImages;
                              payload["reports"] = uiReportsImages;
                              payload["prescription"] = uiPrescriptionImages;

                              bool uploadStatus =
                              await AppSettings.updateRecord(payload,widget.reportDetails.recordId);

                              try {
                                if (uploadStatus) {
                                  Navigator.of(context, rootNavigator: true)
                                      .pop();
                                  AppSettings.longSuccessToast(
                                      'Record updated successfully');
                                  Navigator.pop(context);
                                } else {
                                  Navigator.of(context, rootNavigator: true)
                                      .pop();
                                  AppSettings.longFailedToast(
                                      'Fail to update record details');
                                }
                              } catch (e) {
                                print(e);
                                Navigator.of(context, rootNavigator: true)
                                    .pop();
                                AppSettings.longFailedToast(
                                    'Fail to add record details');
                              }
                            } else {
                              AppSettings.longFailedToast(
                                  'Please check internet');
                            }
                          } else {
                            AppSettings.longFailedToast(
                                'Please enter valid details');
                          }
                        },
                        child: const Text('Update Report'),
                      )),
                ],
              ),
            ),
          ),
        ));
  }
}
