import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:healthcare_user/Reports/add_reports.dart';
import 'package:healthcare_user/common/settings.dart';
import 'package:healthcare_user/common/zoom_image.dart';
import 'package:healthcare_user/models/pharmacies_model.dart';
import 'package:healthcare_user/models/reports_model.dart';
import 'package:healthcare_user/prescriptions/add_prescriptions.dart';
import 'package:healthcare_user/prescriptions/oreder_medicines.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'package:healthcare_user/models/prescriptions_model.dart';
import 'package:intl/intl.dart';

class Prescriptions extends StatefulWidget {
  const Prescriptions({Key? key}) : super(key: key);

  @override
  State<Prescriptions> createState() => _PrescriptionsState();
}

class _PrescriptionsState extends State<Prescriptions> {
  final ImagePicker _picker = ImagePicker();
  String Url = '';
  List<PharmaciesModel> pharmaciesList = [];
  List<ReportsModel> reportsList = [];
  List<ReportsModel> reportsListOriginal = [];
  List<PharmaciesModel> FilteredList = [];
  bool isPharmacyDataLoading = false;
  bool isPrescriptionsDataLoading = false;
  bool isSereverIssue = false;
  double lat = 0;
  double lng = 0;
  String userAddress = '';
  String dropdownArea = '2';
  //String dropdownType = 'Tank';
  var AreaItems = ['2', '5', '10', '25', '50', '100'];
  List pharmaciesCheckboxes = [];
  bool isLoading=false;
  final ImagePicker imagePicker = ImagePicker();
  List imageFileList = [];
  List uiPrescriptionImages = [];
  TextEditingController searchController = TextEditingController();
  TextEditingController dateInput = TextEditingController();
  String dropdownSearchType = 'Problem';
  var typeOfSearchItems = [
    'Problem',
    'Doctor',
    'Date',
  ];

  Future<void> getAllPharmaciesData(var distance) async {
    isPharmacyDataLoading=true;
    try {
      var pharmacyResponse = await AppSettings.getAllpharmacies();

      setState(() {
        pharmaciesList = ((jsonDecode(pharmacyResponse)['data']) as List)
            .map((dynamic model) {
          return PharmaciesModel.fromJson(model);
        }).toList();
        FilteredList = [];
        pharmaciesList.forEach((element) async {
          var distanceInM;
          if (distance == '2') {
            distanceInM = 2000;
          } else if (distance == '5') {
            distanceInM = 5000;
          } else if (distance == '10') {
            distanceInM = 10000;
          } else if (distance == '25') {
            distanceInM = 25000;
          } else if (distance == '50') {
            distanceInM = 50000;
          } else if (distance == '100') {
            distanceInM = 100000;
          }
          double distanceInMeters = await Geolocator.distanceBetween(
              element.lat, element.lng, lat, lng);
          if (distanceInMeters <= distanceInM) {
            FilteredList.add(element);
          }
        });

        isPharmacyDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPharmacyDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  /*Future<void> getAllPrescriptions() async {
    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllPrescriptions();

      setState(() {
        prescriptionsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return PrescriptionsModel.fromJson(model);
        }).toList();
        prescriptionsList=prescriptionsListOriginal.reversed.toList();
        isPrescriptionsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPrescriptionsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }*/


  Future<void> getAllRecords() async {
    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords();

      setState(() {
        reportsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return ReportsModel.fromJson(model);
        }).toList();
        reportsList=reportsListOriginal.reversed.toList();
        isPrescriptionsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPrescriptionsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByProblemName(var problem) async {

    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords();

      setState(() {
        reportsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return ReportsModel.fromJson(model);
        }).toList();
        reportsList=reportsListOriginal.reversed.toList();
        reportsList= reportsListOriginal.where(
                (x) => x.problem.toString().toLowerCase().contains(problem.toString().toLowerCase())
        ).toList();
        isPrescriptionsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPrescriptionsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByDoctorName(var doctor) async {

    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords();

      setState(() {
        reportsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return ReportsModel.fromJson(model);
        }).toList();
        reportsList=reportsListOriginal.reversed.toList();
        reportsList= reportsListOriginal.where(
                (x) => x.doctorName.toString().toLowerCase().contains(doctor.toString().toLowerCase())
        ).toList();
        isPrescriptionsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPrescriptionsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  Future<void> getRecordsByDate(var date) async {

    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllRecords();

      setState(() {
        reportsListOriginal = ((jsonDecode(response)) as List)
            .map((dynamic model) {
          return ReportsModel.fromJson(model);
        }).toList();
        reportsList=reportsListOriginal.reversed.toList();
        reportsList= reportsListOriginal.where(
                (x) => x.date.toString().toLowerCase().contains(date.toString().toLowerCase())
        ).toList();
        isPrescriptionsDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isPrescriptionsDataLoading = false;
        isSereverIssue = true;
      });
    }
  }

  @override
  void initState() {
    lat = AppSettings.userLatitude;
    lng = AppSettings.userLongitude;
    userAddress = AppSettings.userAddress;
    getAllRecords();
    //getAllPharmaciesData(dropdownArea);
    super.initState();
  }

  Future pickImageFromGallery() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final imageTemp = File(image.path);

      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.uploadImageHTTPForPrescriptions(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        Url = jsonDecode(res)['pictures'][0];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  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.uploadImageHTTPForPrescriptions(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        Url = jsonDecode(res)['pictures'][0];
      });
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }


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

    var res = await AppSettings.updatePrescriptionsGallery(imageFileList,recordId);
    print(jsonDecode(res));
    Navigator.of(context, rootNavigator: true).pop();
    getAllRecords();
  }

  Future takeImageFromCameraForUpdate(var recordId) 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,recordId);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      getAllRecords();

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

  Widget _pharamciesData() {
    if (FilteredList.length != 0) {
      return Column(
        children: [
          GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: FilteredList.length,
            itemBuilder: (context, index) {
              return Card(
                elevation: 2.0,
                child: CheckboxListTile(
                  title: Padding(
                    padding: EdgeInsets.fromLTRB(10, 10, 0, 0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: MediaQuery.of(context).size.width * .18,
                          height:
                          MediaQuery.of(context).size.height * .10,
                          decoration: BoxDecoration(
                              shape: BoxShape.rectangle,
                              image: DecorationImage(
                                  image: FilteredList[index].picture == ''
                                      ? AssetImage("images/logo.png")
                                      : NetworkImage(
                                      FilteredList[index].picture)
                                  as ImageProvider, // picked file
                                  fit: BoxFit.contain)),
                        ),
                        SizedBox(
                          width: 5,
                        ),
                        Expanded(
                          child: Container(
                              width:
                              MediaQuery.of(context).size.width * .70,
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                                crossAxisAlignment:
                                CrossAxisAlignment.start,
                                children: [
                                  Text(
                                      FilteredList[index]
                                          .pharmacy_name
                                          .toUpperCase(),
                                      style: wrapTextStyleBlack()),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Text(
                                      FilteredList[index]
                                          .contact_number
                                          .toUpperCase(),
                                      style: wrapTextStyleBlack()),
                                  /*Visibility(
                                  visible: FilteredList[index].supplier_alternate_phone_number!='',
                                  child: Text(
                                      FilteredList[index]
                                          .supplier_alternate_phone_number
                                          .toUpperCase(),
                                      style: wrapTextStyleBlack()),),*/
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Text(
                                      FilteredList[index]
                                          .pharmacy_address
                                          .toUpperCase(),
                                      style: wrapTextStyleBlack()),
                                  Visibility(
                                    visible:
                                    FilteredList[index].description !=
                                        '',
                                    child: SizedBox(
                                      height: 10,
                                    ),
                                  ),
                                  Visibility(
                                    visible:
                                    FilteredList[index].description !=
                                        '',
                                    child: Text(
                                        FilteredList[index]
                                            .description
                                            .toUpperCase(),
                                        style: wrapTextStyleBlack()),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  /*Text(
                                    FilteredList[index]
                                        .starting_price
                                        .toUpperCase(),
                                    style: wrapTextStyleBlack()),
                                SizedBox(height: 10,),*/
                                ],
                              )),
                        ),
                      ],
                    )
                  ),
                  checkColor: Colors.white,
                  activeColor: primaryColor,
                  value: FilteredList[index].isChecked,
                  onChanged: (val) {
                    setState(
                          () {
                            FilteredList[index].isChecked = val!;
                      },
                    );
                    if (FilteredList[index].isChecked) {
                      pharmaciesCheckboxes.add({

                        'pharmacyId':
                        FilteredList[index]
                            .pharmacy_id,

                      });
                    } else {
                      pharmaciesCheckboxes.removeWhere((e) =>
                      e['pharmacyId']
                          .toString()
                          .toUpperCase() ==
                          FilteredList[index]
                              .pharmacy_id
                              .toString()
                              .toUpperCase());
                    }
                  },
                ),
              );
            },
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 1,//.size.width * .33,
                childAspectRatio: MediaQuery.of(context).size.width /
                    (MediaQuery.of(context).size.height /7)),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              primary: primaryColor, // background
              onPrimary: Colors.white, // foreground
            ),
            onPressed: () async {
              if(Url!=''&&pharmaciesCheckboxes.isNotEmpty){

                AppSettings.preLoaderDialog(context);

                var payload = new Map<String, dynamic>();

                payload["picture"] = Url.toString();
                payload["pharmacies"] = pharmaciesCheckboxes;
                bool status = await AppSettings.getQuotation(payload);
                try {
                  if (status) {
                    Navigator.of(context, rootNavigator: true).pop();
                    Url='';
                    pharmaciesCheckboxes = [];
                    AppSettings.longSuccessToast(
                        "Prescription uploaded Successfully");
                   // Navigator.pop(context);
                    getAllPharmaciesData(dropdownArea);
                    /*
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ConnectionsView()),
                    );*/
                  } else {
                    Navigator.of(context, rootNavigator: true).pop();
                    AppSettings.longFailedToast(
                        "Failed to upload prescription");
                  }
                } catch (exception) {
                  AppSettings.longFailedToast("Failed to upload prescription");
                  print(exception);
                }

              }
              else{
                AppSettings.longFailedToast('Please select image and pharmacies' );
              }
            },
            child: const Text('Upload'),
          )
        ],
      );
    } else {
      return Center(
          child: Padding(
        padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
        child: isSereverIssue
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image(
                    image: AssetImage('images/serverissue.png'),
                    //  height: MediaQuery.of(context).size.height * .10,
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Text(
                    'There is an issue at server please try after some time',
                    style: serverIssueTextStyle(),
                  ),
                ],
              )
            : userAddress == ''
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      /*Image(
                  image: AssetImage('images/resourceblue.pngs'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),*/
                      Icon(
                        Icons.location_on_outlined,
                        color: primaryColor,
                        size: 40,
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text(
                        'Please select location to see near by pharmacies',
                        style: TextStyle(
                          color: primaryColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image(
                        image: AssetImage('images/no_data.png'),
                        //  height: MediaQuery.of(context).size.height * .10,
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text(
                        'No Pharmacies',
                        style: serverIssueTextStyle(),
                      ),
                    ],
                  ),
      ));
    }
  }
  showPicDialog(var imageUrl){
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return AlertDialog(
                title: const Text(''),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Container(
                          width: MediaQuery.of(context).size.width * .10,
                          height: MediaQuery.of(context).size.height * .50,
                          child: PhotoView(
                            imageProvider: NetworkImage(imageUrl) as ImageProvider,
                            maxScale: PhotoViewComputedScale.contained * 4.0,
                            minScale: PhotoViewComputedScale.contained,
                            initialScale: PhotoViewComputedScale.contained,
                            basePosition: Alignment.center,

                          )
                      )
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: Text('Close', style: textButtonStyle()),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      },
    );
  }

  Widget prescriptions(var obj){
    if(obj.prescriptionImages.length!=0){
      return Container(
        //color: secondaryColor,
        width: double.infinity,
        height: MediaQuery.of(context).size.height * .20,
        child: Row(
          children: [
           Expanded(child:  ListView.builder(
               scrollDirection: Axis.horizontal,
               itemCount: obj.prescriptionImages.length,
               itemBuilder: (context, index) {
                 return Row(
                   children: [
                     Card(
                       child: GestureDetector(
                         onTap: (){
                           //showPicDialog(obj.prescriptionImages[index]['url']);
                           Navigator.push(
                               context,
                               new MaterialPageRoute(
                                   builder: (__) => new ImageZoomPage(imageName:'Prescriptions',imageDetails:obj.prescriptionImages[index]['url'])));},
                         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(
                                       obj.prescriptionImages[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);

                                               String fileName = obj.prescriptionImages[index]['url']
                                                   .split('/')
                                                   .last;

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

                                               try {
                                                 var res = await AppSettings
                                                     .deleteRecordsNew(
                                                     payload,
                                                     obj.recordId);
                                                 print(jsonDecode(res));
                                                 Navigator.of(context,
                                                     rootNavigator: true)
                                                     .pop();
                                                 Navigator.of(context).pop(true);
                                                 AppSettings.longSuccessToast(
                                                     "Image deleted Successfully");
                                                 setState(() {
                                                   obj.prescriptionImages =
                                                   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,
                                                 )),
                                           ),
                                         ],
                                       ),
                                     );
                                   },
                                 ),
                               ),
                             )
                           ]),
                         ),
                       ),
                     )

                   ],
                 );
               }),),
            IconButton(
              iconSize: 40,
              icon: const Icon(
                Icons.add,
                color: Colors.green,
              ),
              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(obj.recordId);
                                  Navigator.pop(context);
                                },
                              ),
                              SizedBox(
                                width: MediaQuery.of(context).size.width *
                                    .20,
                              ),
                              GestureDetector(
                                child: Icon(
                                  Icons.photo,
                                  size: 100,
                                  color: primaryColor,
                                ),
                                onTap: () async {
                                  await pickImageFromGalleryForUpdate(obj.recordId);
                                  Navigator.pop(context);
                                },
                              ),
                            ],
                          ),
                        ),
                      );
                    });



              },
            )

          ],
        )
      );
    }
    else{
     return Row(
       children: [
       IconButton(
       iconSize: 40,
       icon: const Icon(
         Icons.add,
         color: Colors.green,
       ),
       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(obj.recordId);
                           Navigator.pop(context);
                         },
                       ),
                       SizedBox(
                         width: MediaQuery.of(context).size.width *
                             .20,
                       ),
                       GestureDetector(
                         child: Icon(
                           Icons.photo,
                           size: 100,
                           color: primaryColor,
                         ),
                         onTap: () async {
                           await pickImageFromGalleryForUpdate(obj.recordId);
                           Navigator.pop(context);
                         },
                       ),
                     ],
                   ),
                 ),
               );
             });



       },
     ),
         Text('Add Prescriptions',style: textButtonStyle(),)
       ],
     );
    }



  }

  Widget _filtereddata(){
    if (reportsList.length != 0) {
      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: reportsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Visibility(
                    visible: true,
                      child: Card(

                    //color: prescriptionsList[index].cardColor,
                    child: Padding(
                      padding:EdgeInsets.all(8) ,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [

                              Container(
                                width: MediaQuery.of(context).size.width * .55,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('Problem: '+reportsList[index].problem.toString().toUpperCase(),style: problemTextStyle()),
                                    Text(reportsList[index].doctorName.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(reportsList[index].hospitalName.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(reportsList[index].date.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(reportsList[index].patient_name.toString().toUpperCase(),style: valuesTextStyle()),
                                    Row(
                                      children: [
                                        Text(reportsList[index].gender.toString().toUpperCase(),style: valuesTextStyle()),
                                        SizedBox(width:MediaQuery.of(context).size.width * .05,),
                                        Text(reportsList[index].age.toString().toUpperCase()+" Yrs",style: valuesTextStyle()),
                                      ],
                                    ),


                                  ],
                                ),


                              ),
                            ],

                          ),

                          SizedBox(height:MediaQuery.of(context).size.height * .02,),

                          prescriptions(reportsList[index]),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.shopping_cart,
                                color: primaryColor,
                              ),
                              TextButton(
                              child:  Text(
                                'Order Medicines / Other Products',
                                style: textButtonStyle(),
                              ),
                              onPressed: () {

                                Navigator.push(
                                    context,
                                    new MaterialPageRoute(
                                        builder: (__) => new OrderMedicines(prescriptionDetails:reportsList[index])));
                                //signup screen
                              },
                            )],
                          )
                        ],
                      ),
                    ),
                  ));
                }) ),
          ]);
    }
    else{
      return   Padding(padding: EdgeInsets.fromLTRB(60,10,60,10),
        child: Column(
          children: [
            Text('No prescriptions found related to your search'),
            SizedBox(
              height: 20,
            ),
            CircleAvatar(
              backgroundColor: Colors.red,
              radius: 30,
              child: const Icon(
                Icons.info,
                color: Colors.white,
              ),
            )
          ],
        ),);
    }
  }

  Widget _allPrescriptions(){

    if(reportsListOriginal.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
              child: DropdownButtonFormField(
                // Initial Value
                value: dropdownSearchType,
                isExpanded: true,
                decoration: const InputDecoration(
                  prefixIcon: Icon(
                    Icons.search,
                    color: greyColor,
                  ),
                  border: OutlineInputBorder(
                      borderSide: BorderSide(color: greyColor)),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: greyColor),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: greyColor),
                  ),
                  labelText: 'Search By',
                  labelStyle: TextStyle(
                    color: greyColor, //<-- SEE HERE
                  ),
                ),

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

                // Array list of items
                items: typeOfSearchItems.map((String items) {
                  return DropdownMenuItem(
                    value: items,
                    child: Text(items),
                  );
                }).toList(),
                // After selecting the desired option,it will
                // change button value to selected value
                onChanged: (String? newValue) {
                  setState(() {
                    dropdownSearchType = newValue!;
                  });
                },
              ),
            ),
            Visibility(
              visible:dropdownSearchType.toString().toLowerCase()=='problem' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByProblemName(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      /*suffixIcon: Icon(
                              Icons.clear,
                              color: greyColor,
                            ),*/
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by problem',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),),
            Visibility(
              visible:dropdownSearchType.toString().toLowerCase()=='doctor' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByDoctorName(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      /*suffixIcon: Icon(
                              Icons.clear,
                              color: greyColor,
                            ),*/
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by doctor',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),),
            Visibility(
              visible:dropdownSearchType.toString().toLowerCase()=='date' ,
              child: Container(
                  height: MediaQuery.of(context).size.height * .07,
                  padding:  EdgeInsets.all(5),
                  child: Center(child: TextField(

                    cursorColor: primaryColor,
                    controller: searchController,
                    onChanged: (string) {
                      if(string.length>=1){
                        getRecordsByDate(string);
                      }
                      else{
                        getAllRecords();
                      }
                    },
                    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(() {
                          searchController.text = formattedDate; //set output date to TextField value.
                        });
                        getRecordsByDate(searchController.text);
                      } else {}
                    },
                    decoration:  InputDecoration(
                      prefixIcon: Icon(
                        Icons.search,
                        color: primaryColor,
                      ),
                      suffixIcon: searchController.text!=''?IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            searchController.text='';
                          });
                          getAllRecords();
                        },
                      ):IconButton(
                        icon:  Icon(
                          Icons.clear,
                          color: Colors.transparent,
                        ),
                        onPressed: () {
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: primaryColor),
                        borderRadius: BorderRadius.circular(30),
                      ),
                      //labelText: 'Search by phone number',
                      hintText: 'Search by date',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),)
              ),


            ),
            Expanded(child: _filtereddata()),
            Padding(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: CircleAvatar(
                backgroundColor: primaryColor,
                radius: 40,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    IconButton(
                      iconSize: 40,
                      icon: const Icon(
                        Icons.add,
                        color: Colors.white,
                      ),
                      onPressed: () async{
                        /*await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => AddPrescription()),
                        );*/
                        Navigator.push(context, MaterialPageRoute(builder: (context) => AddReports())).then((value) {
                          getAllRecords();
                        });
                        //showBoreAddingDialog();
                      },
                    ),
                    /* Padding(
                      padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
                      child: Text(
                        'Add Tanks ',
                        style: TextStyle(color: Colors.white),
                      ),
                    )*/
                  ],
                ),
              ),
            ),
          ]);


    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('Click below icon to add new Record'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      Navigator.push(context, MaterialPageRoute(builder: (context) => AddReports())).then((value) {
                        getAllRecords();
                      });
                    },
                  ),
                )
              ],
            ),
          )
      );
    }


  }

  /**/

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Prescriptions'),
      body: isPrescriptionsDataLoading?Center(
        child: CircularProgressIndicator(
          color: primaryColor,
          strokeWidth: 5.0,
        ),
      ): _allPrescriptions(),
    );
  }
}
