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:doctor/models/get_connected_doctors_model.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';

class AddReports extends StatefulWidget {
  String? customerId;
  String? patName;
  String? patAge;
  String? patGender;
  AddReports({this.customerId,this.patName,this.patAge,this.patGender});


  @override
  State<AddReports> createState() => _AddReportsState();
}

class _AddReportsState extends State<AddReports> {

  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 = [];
  Map<String,dynamic> findings={};
  List<Asset> images = <Asset>[];
  String _error = 'No Error Dectected';
  String apiMultiImages = '';
  String findingPictureId = '';
  String reportsPictureId = '';
  String prescriptionPictureId = '';
  Map<String,dynamic> reports={};
  Map<String,dynamic> prescriptions={};
  String? prescriptionFor;
  String? problemCategory;
  String? gender;
  var doctorNameVariable;
  List<GetConnectedDoctorsModel> connectedDoctorsListOriginal = [];

  Future<void> getAllConnectedDoctors() async {
    try {
      var response = await AppSettings.getAllConnectedDoctors(widget.customerId);

      setState(() {
        connectedDoctorsListOriginal = ((jsonDecode(response)['doctors']) as List)
            .map((dynamic model) {
          return GetConnectedDoctorsModel.fromJson(model);
        }).toList();
        //connectedDoctorsListOriginal=connectedDoctorsListOriginal.reversed.toList();
        //dateItemsVariable=connectedDoctorsListOriginal[0].doctor_name;
      });
    } catch (e) {
      AppSettings.longFailedToast('There is an issue please wait some time');
    }
  }

  @override
  void initState() {
    getAllConnectedDoctors();
    super.initState();
  }

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

    var res = await AppSettings.uploadFindingsGallery(imageFileList,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiFindingsImages = jsonDecode(res)['findingsPictureUpload']['findings'];
      findings=jsonDecode(res)['findingsPictureUpload'];
      findingPictureId=jsonDecode(res)['findingsPictureUpload']['findingsPictureId'];

    });
  }

  Future takeImageFromCamera() 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.uploadFindingsCamera(image,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiFindingsImages = jsonDecode(res)['findingsPictureUpload']['findings'];
        findings=jsonDecode(res)['findingsPictureUpload'];
        findingPictureId=jsonDecode(res)['findingsPictureUpload']['findingsPictureId'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

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

    var res = await AppSettings.addFindingsGallery(imageFileList,findingPictureId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiFindingsImages = jsonDecode(res)['findingsPictureUpload']['findings'];
      findings=jsonDecode(res)['findingsPictureUpload'];
      findingPictureId=jsonDecode(res)['findingsPictureUpload']['findingsPictureId'];

    });
  }

  Future takeImageFromCameraForAddFindings() 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.addFindingsCamera(image,findingPictureId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiFindingsImages = jsonDecode(res)['findingsPictureUpload']['findings'];
        findings=jsonDecode(res)['findingsPictureUpload'];
        findingPictureId=jsonDecode(res)['findingsPictureUpload']['findingsPictureId'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future takeImageFromCameraForReports() 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.uploadReportsCamera(image,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiReportsImages = jsonDecode(res)['reportsPictureUpload']['reports'];
        reports=jsonDecode(res)['reportsPictureUpload'];
        reportsPictureId=jsonDecode(res)['reportsPictureUpload']['reportsPictureId'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

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

    var res = await AppSettings.uploadReportsGallery(imageFileListReports,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiReportsImages = jsonDecode(res)['reportsPictureUpload']['reports'];
      reports=jsonDecode(res)['reportsPictureUpload'];
      reportsPictureId=jsonDecode(res)['reportsPictureUpload']['reportsPictureId'];
    });
  }

  Future takeImageFromCameraForAddReports() 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.addReportsCamera(image,reportsPictureId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiReportsImages = jsonDecode(res)['reportsPictureUpload']['reports'];
        reports=jsonDecode(res)['reportsPictureUpload'];
        reportsPictureId=jsonDecode(res)['reportsPictureUpload']['reportsPictureId'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

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

    var res = await AppSettings.addReportsGallery(imageFileListReports,reportsPictureId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiReportsImages = jsonDecode(res)['reportsPictureUpload']['reports'];
      reports=jsonDecode(res)['reportsPictureUpload'];
      reportsPictureId=jsonDecode(res)['reportsPictureUpload']['reportsPictureId'];
    });
  }

  Future takeImageFromCameraForPrescriptions() 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.uploadPrescriptionsCamera(image,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {

        uiPrescriptionImages = jsonDecode(res)['prescriptionsPictureUpload']['precription'];
        prescriptions=jsonDecode(res)['prescriptionsPictureUpload'];
        prescriptionPictureId=jsonDecode(res)['prescriptionsPictureUpload']['prescriptionPictureId'];

      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

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

    var res = await AppSettings.uploadPrescriptionsGallery(
        imageFileListPrescriptions,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiPrescriptionImages = jsonDecode(res)['prescriptionsPictureUpload']['precription'];
      prescriptions=jsonDecode(res)['prescriptionsPictureUpload'];
      prescriptionPictureId=jsonDecode(res)['prescriptionsPictureUpload']['prescriptionPictureId']??'';
    });
  }

  Future takeImageFromCameraForAddPrescriptions() 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.addPrescriptionsCamera(image,prescriptionPictureId,widget.customerId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        uiPrescriptionImages = jsonDecode(res)['prescriptionsPictureUpload']['precription'];
        prescriptions=jsonDecode(res)['prescriptionsPictureUpload'];
        prescriptionPictureId=jsonDecode(res)['prescriptionsPictureUpload']['prescriptionPictureId'];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

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

    var res = await AppSettings.addPrescriptionsGallery(imageFileListPrescriptions,prescriptionPictureId,widget.customerId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    setState(() {
      uiPrescriptionImages = jsonDecode(res)['prescriptionsPictureUpload']['precription'];
      prescriptions=jsonDecode(res)['prescriptionsPictureUpload'];
      prescriptionPictureId=jsonDecode(res)['prescriptionsPictureUpload']['prescriptionPictureId'];
    });
  }

  Future<bool> onWillPop() async {
    final shouldPop = await showDialog<bool>(context: context, builder: (context) {
      return AlertDialog(
        title: const Text('Do you want to leave this page',
            style: TextStyle(
              color: primaryColor,
              fontSize: 20,
            )),
        actionsAlignment: MainAxisAlignment.spaceBetween,
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(true);
            },
            child: const Text('Yes',
                style: TextStyle(
                  color: primaryColor,
                  fontSize: 20,
                )),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(false);
            },
            child: const Text('No',
                style: TextStyle(
                  color: primaryColor,
                  fontSize: 20,
                )),
          ),
        ],
      );
    },
    );
    return shouldPop!;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => onWillPop(),
      child: Scaffold(
          appBar: AppSettings.appBar('Add Record'),
          body: SingleChildScrollView(
            child: Container(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      child: connectedDoctorsListOriginal.length!=0?DropdownButtonFormField(
                      value: doctorNameVariable,
                      isExpanded: true,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(
                          Icons.person,
                          color: greyColor,
                        ),
                        border: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor)),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        labelText: 'Select Doctor',
                        labelStyle: TextStyle(
                          color: greyColor, //<-- SEE HERE
                        ),
                      ),

                      hint: Text('Please Select Doctor'),
                      // Down Arrow Icon
                      //icon: const Icon(Icons.keyboard_arrow_down),

                      // Array list of items
                      items: connectedDoctorsListOriginal.map((items) {
                        return DropdownMenuItem(
                            value: items,
                            child: Text(
                              items.doctor_name,
                              style: TextStyle(
                                fontSize: 16,
                              ),
                              textAlign: TextAlign.center,
                            ));
                      }).toList(),
                      // After selecting the desired option,it will
                      // change button value to selected value
                      onChanged: ( newValue) {
                        setState(() {
                          doctorNameVariable = newValue;
                        });
                      },
                    ):
                    IconButton(
                      onPressed: () {
                        /*Navigator.push(context, MaterialPageRoute(builder: (context) => AddDoctor())).then((value) {
                          getAllConnectedDoctors();
                        });*/
                      },
                      icon: Icon(
                        Icons.add,
                        color: primaryColor,
                        size: 40,
                      ),
                    ),),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * .02,
                    ),
                    Container(
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: problemController,
                        textCapitalization: TextCapitalization.words,
                        decoration: textFormFieldDecorationGrey(
                            Icons.report_problem, 'Enter Problem'),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * .02,
                    ),
                    Container(
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: dateInput,
                        decoration: textFormFieldDecorationGrey(
                            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 {}
                        },
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * .02,
                    ),
                    Text('Select Problem Category',
                      style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold,fontSize: 14),),
                    Row(
                      children: [
                        Expanded(
                          child: RadioListTile(
                            title: Text("General"),
                            value: "general",
                            groupValue: problemCategory,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                problemCategory = value.toString();
                              });
                            },
                          ),
                        ),
                        Expanded(
                          child: RadioListTile(
                            title: Text("Confidential"),
                            value: "confidential",
                            groupValue: problemCategory,
                            activeColor: primaryColor,
                            onChanged: (value) {
                              setState(() {
                                problemCategory = value.toString();
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                    Text('Select Problem For',
                      style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold,fontSize: 14),),
                    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 takeImageFromCamera();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGallery();
                                            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.cancel,
                                                    color: Colors.red,
                                                  ),
                                                  onPressed: () async {
                                                    AppSettings.preLoaderDialog(context);

                                                    String fileName = uiFindingsImages[index]['url'].split('/').last;
                                                    try{
                                                      var response = await AppSettings.deleteFindings(fileName,findingPictureId,widget.customerId);
                                                      print(jsonDecode(response));
                                                      Navigator.of(context, rootNavigator: true).pop();
                                                      setState(() {
                                                        uiFindingsImages = jsonDecode(response)['findingsPictureUpload']['findings'];
                                                      });
                                                    }
                                                    catch(e){
                                                      Navigator.of(context, rootNavigator: true).pop();
                                                      AppSettings.longFailedToast('Image deletion failed');
                                                    }

                                                  },
                                                ),
                                              ),
                                            )
                                          ]),
                                        ),
                                      ),
                                    ),
                                    /*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 takeImageFromCameraForAddFindings();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGalleryForAddFindings();
                                            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 takeImageFromCameraForReports();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGalleryForReports();
                                            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.cancel,
                                                      color: Colors.red,
                                                    ),
                                                    onPressed: () async {
                                                      AppSettings.preLoaderDialog(context);

                                                      String fileName = uiReportsImages[index]['url'].split('/').last;
                                                      var response = await AppSettings.deleteReports(fileName,reportsPictureId,widget.customerId);
                                                      print(jsonDecode(response));
                                                      Navigator.of(context, rootNavigator: true).pop();
                                                      setState(() {
                                                        uiReportsImages = jsonDecode(response)['reportsPictureUpload']['reports'];
                                                      });

                                                    },
                                                  ),
                                                ),
                                              )
                                            ]),
                                          ),
                                        )
                                    ),
                                    /*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 takeImageFromCameraForAddReports();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGalleryForAddReports();
                                            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 takeImageFromCameraForPrescriptions();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGalleryForPrescriptions();
                                            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.cancel,
                                                      color: Colors.red,
                                                    ),
                                                    onPressed: () async {
                                                      AppSettings.preLoaderDialog(context);

                                                      String fileName = uiPrescriptionImages[index]['url'].split('/').last;
                                                      var response = await AppSettings.deletePrescriptions(fileName,prescriptionPictureId,widget.customerId);
                                                      print(jsonDecode(response));
                                                      Navigator.of(context, rootNavigator: true).pop();
                                                      setState(() {
                                                        uiPrescriptionImages = jsonDecode(response)['prescriptionsPictureUpload']['precription'];
                                                      });

                                                    },
                                                  ),
                                                ),
                                              )
                                            ]),
                                          ),
                                        )
                                    ),
                                    /*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 takeImageFromCameraForAddPrescriptions();
                                            Navigator.pop(context);
                                          },
                                        ),
                                        SizedBox(
                                          width:
                                          MediaQuery.of(context).size.width *
                                              .20,
                                        ),
                                        GestureDetector(
                                          child: Icon(
                                            Icons.photo,
                                            size: 100,
                                            color: primaryColor,
                                          ),
                                          onTap: () async {
                                            await pickImageFromGalleryForAddPrescriptions();
                                            Navigator.pop(context);
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              });
                        },
                        child: const Text('Add Prescriptions'),
                      ),
                    ),

                    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 (doctorNameVariable!=''&&problemController.text != '' &&
                                dateInput.text != '' &&
                                prescriptionFor != ''&&problemCategory!='') {
                              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 {
                                _name = widget.patName!;
                                _age = widget.patAge!;
                                _gender = widget.patGender!;
                              }
                              AppSettings.preLoaderDialog(context);
                              bool isOnline =
                              await AppSettings.internetConnectivity();
                              if (isOnline) {
                                var payload = new Map<String, dynamic>();
                                payload["problem"] =
                                    problemController.text.toString();
                                payload["doctorName"] = doctorNameVariable.doctor_name.toString();
                                payload["hospitalName"] = doctorNameVariable.hospital_name.toString();
                                payload["doctorId"] = doctorNameVariable.doctor_id.toString();
                                payload["date"] = dateInput.text.toString();
                                payload["findings_date"] = '';
                                payload["reports_date"] = '';
                                payload["prescription_date"] = '';
                                payload["patientType"] = prescriptionFor.toString();
                                payload["problemCategory"] = problemCategory.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.addRecords(payload,widget.customerId);

                                try {
                                  if (uploadStatus) {
                                    Navigator.of(context, rootNavigator: true)
                                        .pop();
                                    AppSettings.longSuccessToast(
                                        'Record added successfully');
                                    Navigator.pop(context);
                                  } else {
                                    Navigator.of(context, rootNavigator: true)
                                        .pop();
                                    AppSettings.longFailedToast(
                                        'Fail to add 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('Submit'),
                        )),
                  ],
                ),
              ),
            ),
          ))
    );
  }

}
