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/common/settings.dart';
import 'package:healthcare_user/models/pharmacies_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';

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<PrescriptionsModel> prescriptionsList = [];
  List<PrescriptionsModel> prescriptionsListOriginal = [];
  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;

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

  @override
  void initState() {
    lat = AppSettings.userLatitude;
    lng = AppSettings.userLongitude;
    userAddress = AppSettings.userAddress;
    getAllPrescriptions();
    //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');
    }
  }

  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 _allPrescriptions(){
    if (prescriptionsList.length != 0) {
      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: prescriptionsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return 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: [
                              GestureDetector(
                                child: Container(
                                  width: MediaQuery.of(context).size.width * .18,
                                  height:
                                  MediaQuery.of(context).size.height * .10,
                                  decoration: BoxDecoration(
                                      shape: BoxShape.rectangle,
                                      image: DecorationImage(
                                          image: NetworkImage(prescriptionsList[index].prescription_url) as ImageProvider, // picked file
                                          fit: BoxFit.contain)),
                                ),
                                onTap: (){
                                  showPicDialog(prescriptionsList[index].prescription_url);

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

                              Container(
                                width: MediaQuery.of(context).size.width * .55,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(prescriptionsList[index].prescription_name.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(prescriptionsList[index].patient_name.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(prescriptionsList[index].gender.toString().toUpperCase(),style: valuesTextStyle()),
                                    Text(prescriptionsList[index].age.toString().toUpperCase(),style: valuesTextStyle()),
                                  ],
                                ),


                              ),


                              Expanded(child:IconButton(
                                icon: const Icon(Icons.edit,color: primaryColor,),
                                onPressed: () {


                                },
                              ),),
                              Expanded(child:IconButton(
                                icon: const Icon(Icons.delete,color: primaryColor,),

                                onPressed: () async{
                                  /*  showDialog(
                                //if set to true allow to close popup by tapping out of the popup
                                //barrierDismissible: false,
                                context: context,
                                builder: (BuildContext context) => AlertDialog(
                                  title: const Text('Do you want to delete tank?',
                                      style: TextStyle(
                                        color: primaryColor,
                                        fontSize: 20,
                                      )),
                                  actionsAlignment: MainAxisAlignment.spaceBetween,
                                  actions: [
                                    TextButton(
                                      onPressed: ()async {
                                        var payload = new Map<String, dynamic>();
                                        payload["tankLocation"] = modelTanksViewList[index].tank_location.toString().toLowerCase();
                                        bool deleteTankStatus = await AppSettings.deleteTank(modelTanksViewList[index].tank_name,payload);


                                        if(deleteTankStatus){
                                          readJson();
                                          AppSettings.longSuccessToast('tank deleted successfully');
                                          Navigator.of(context).pop(true);

                                        }
                                        else{
                                          AppSettings.longFailedToast('tank deletion failed');
                                          Navigator.of(context).pop(true);
                                        }
                                      },
                                      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,
                                          )),
                                    ),
                                  ],
                                ),
                              );*/



                                },
                              ),)

                            ],

                          ),
                          TextButton(
                            child: const Text(
                              'Order Medicines',
                              style: TextStyle(color: primaryColor),
                            ),
                            onPressed: () {

                              Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (__) => new OrderMedicines(prescriptionDetails:prescriptionsList[index])));
                              //signup screen
                            },
                          )
                        ],
                      ),
                    ),
                  );
                }) ),
            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) => AddPrescription())).then((value) {
                          getAllPrescriptions();
                        });
                        //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 prescription'),
                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) => AddPrescription())).then((value) {
                        getAllPrescriptions();
                      });
                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }

  /**/

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