import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/model/Prescription_model.dart';
import 'package:doctor_app_flutter/core/model/get_medication_response_model.dart';
import 'package:doctor_app_flutter/core/model/post_prescrition_req_model.dart';
import 'package:doctor_app_flutter/core/viewModel/medicine_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/prescription_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentReqModel.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/prescription/drugtodrug.dart';
import 'package:doctor_app_flutter/util/date-utils.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/medicine/medicine_item_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/dialogs/dailog-list-select.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';

addPrescriptionForm(context, PrescriptionViewModel model,
    PatiantInformtion patient, prescription) {
  showModalBottomSheet(
      isScrollControlled: true,
      context: context,
      builder: (BuildContext bc) {
        return PrescriptionFormWidget(model, patient, prescription);
      });
}

postProcedure(
    {String duration,
    String doseTimeIn,
    String dose,
    String drugId,
    String strength,
    String route,
    String frequency,
    String indication,
    String instruction,
    PrescriptionViewModel model,
    DateTime doseTime,
    String doseUnit,
    String icdCode,
    PatiantInformtion patient,
    String patientType}) async {
  PostPrescriptionReqModel postProcedureReqModel =
      new PostPrescriptionReqModel();
  List<PrescriptionRequestModel> sss = List();

  postProcedureReqModel.appointmentNo = patient.appointmentNo;
  postProcedureReqModel.clinicID = patient.clinicId;
  postProcedureReqModel.episodeID = patient.episodeNo;
  postProcedureReqModel.patientMRN = patient.patientMRN;

  sss.add(PrescriptionRequestModel(
      covered: true,
      dose: double.parse(dose),
      itemId: drugId.isEmpty ? 1 : int.parse(drugId),
      doseUnitId: int.parse(doseUnit),
      route: route.isEmpty ? 1 : int.parse(route),
      frequency: frequency.isEmpty ? 1 : int.parse(frequency),
      remarks: instruction,
      approvalRequired: true,
      icdcode10Id: icdCode.toString(),
      doseTime: doseTimeIn.isEmpty ? 1 : int.parse(doseTimeIn),
      duration: duration.isEmpty ? 1 : int.parse(duration),
      doseStartDate: doseTime.toIso8601String()));
  postProcedureReqModel.prescriptionRequestModel = sss;
  //postProcedureReqModel.procedures = controlsProcedure;

  await model.postPrescription(postProcedureReqModel, patient.patientMRN);

  if (model.state == ViewState.ErrorLocal) {
    Helpers.showErrorToast(model.error);
  } else if (model.state == ViewState.Idle) {
    model.getPrescriptions(patient);
    DrAppToastMsg.showSuccesToast('Medication has been added');
  }
}

class PrescriptionFormWidget extends StatefulWidget {
  final PrescriptionViewModel model;
  PatiantInformtion patient;
  List<PrescriptionModel> prescriptionList;
  PrescriptionFormWidget(this.model, this.patient, this.prescriptionList);

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

class _PrescriptionFormWidgetState extends State<PrescriptionFormWidget> {
  int selectedType;
  TextEditingController durationController = TextEditingController();
  TextEditingController strengthController = TextEditingController();
  TextEditingController routeController = TextEditingController();
  TextEditingController frequencyController = TextEditingController();
  TextEditingController indicationController = TextEditingController();
  TextEditingController instructionController = TextEditingController();

  bool visbiltyPrescriptionForm = false;
  bool visbiltySearch = true;

  final myController = TextEditingController();
  DateTime selectedDate;
  dynamic selectedDrug;
  int strengthChar;
  GetMedicationResponseModel _selectedMedication;
  GlobalKey key =
      new GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>>();

  TextEditingController drugIdController = TextEditingController();
  TextEditingController doseController = TextEditingController();
  final searchController = TextEditingController();

  var notesList;
  var filteredNotesList;
  String textSeartch = "Amoxicillin";

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final double spaceBetweenTextFileds = 12;
  List<dynamic> referToList;
  dynamic type;
  dynamic strength;
  dynamic route;
  dynamic frequency;
  dynamic duration;
  dynamic doseTime;
  dynamic indication;
  dynamic units;
  dynamic uom;
  dynamic box;
  dynamic x;

  List<dynamic> indicationList;
  String routeInatial = 'By Mouth';

  //PatiantInformtion patient;
  @override
  void initState() {
    super.initState();
    selectedType = 1;
    referToList = List();

    indicationList = List();

    dynamic indication1 = {"id": 545, "name": "Gingival Hyperplasia"};
    dynamic indication2 = {"id": 546, "name": "Mild Drowsiness"};
    dynamic indication3 = {"id": 547, "name": "Hypertrichosis"};
    dynamic indication4 = {"id": 548, "name": "Mild Dizziness"};
    dynamic indication5 = {"id": 549, "name": "Enlargement of Facial Features"};
    dynamic indication6 = {
      "id": 550,
      "name": "Phenytoin Hypersensitivity Syndrome"
    };
    dynamic indication7 = {"id": 551, "name": "Asterixis"};
    dynamic indication8 = {"id": 552, "name": "Bullous Dermatitis"};
    dynamic indication9 = {"id": 554, "name": "Purpuric Dermatitis"};
    dynamic indication10 = {"id": 555, "name": "Systemic Lupus Erythematosus"};

    indicationList.add(indication1);
    indicationList.add(indication2);
    indicationList.add(indication3);
    indicationList.add(indication4);
    indicationList.add(indication5);
    indicationList.add(indication6);
    indicationList.add(indication7);
    indicationList.add(indication8);
    indicationList.add(indication9);
    indicationList.add(indication10);
  }

  setSelectedType(int val) {
    setState(() {
      selectedType = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    ListSelectDialog drugDialog;
    final screenSize = MediaQuery.of(context).size;

    // final routeArgs = ModalRoute.of(context).settings.arguments as Map;
    // patient = routeArgs['patient'];

    return BaseView<MedicineViewModel>(
      onModelReady: (model) async {
        x = model.patientAssessmentList.map((element) {
          return element.icdCode10ID;
        });
        GetAssessmentReqModel getAssessmentReqModel = GetAssessmentReqModel(
            patientMRN: widget.patient.patientMRN,
            episodeID: widget.patient.episodeNo.toString(),
            editedBy: '',
            doctorID: '',
            appointmentNo: widget.patient.appointmentNo);
        //await model.getMedicationList();
        if (model.medicationStrengthList.length == 0) {
          await model.getMedicationStrength();
        }
        //await model.getPrescription(mrn: widget.patient.patientMRN);
        if (model.medicationDurationList.length == 0) {
          await model.getMedicationDuration();
        }
        //await model.getMedicationRoute();
        //await model.getMedicationFrequency();
        if (model.medicationDoseTimeList.length == 0) {
          await model.getMedicationDoseTime();
        }
        //await model.getMedicationIndications();
        await model.getPatientAssessment(getAssessmentReqModel);
        //await model.getItem();
      },
      builder: (
        BuildContext context,
        MedicineViewModel model,
        Widget child,
      ) =>
          NetworkBaseView(
        baseViewModel: model,
        child: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(new FocusNode());
          },
          child: DraggableScrollableSheet(
              initialChildSize: 0.98,
              maxChildSize: 0.98,
              minChildSize: 0.9,
              builder:
                  (BuildContext context, ScrollController scrollController) {
                return SingleChildScrollView(
                  child: Container(
                    height: MediaQuery.of(context).size.height * 1.45,
                    color: Color(0xffF8F8F8),
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 12.0, vertical: 10.0),
                      child: Column(
                        //crossAxisAlignment: CrossAxisAlignment.start,
                        //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Column(
                            children: [
                              SizedBox(
                                height: 15,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  AppText(
                                    'New Prescription Order',
                                    fontWeight: FontWeight.w700,
                                    fontSize: 20,
                                  ),
                                  InkWell(
                                    child: Icon(
                                      Icons.close,
                                      size: 24.0,
                                    ),
                                    onTap: () {
                                      Navigator.pop(context);
                                    },
                                  )
                                ],
                              ),
                            ],
                          ),
                          SizedBox(
                            height: spaceBetweenTextFileds,
                          ),
                          Container(
                            child: Form(
                              key: formKey,
                              child: Column(
                                //mainAxisAlignment: MainAxisAlignment.end,
                                children: [

                                  FractionallySizedBox(
                                    widthFactor: 0.9,
                                    child: Container(
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(6.0)),
                                          border: Border.all(
                                              width: 1.0,
                                              color: HexColor("#CCCCCC"))),
                                      padding: EdgeInsets.all(10),
                                      child: AppTextFormField(
                                        onTap: () {
                                          visbiltyPrescriptionForm = false;
                                          visbiltySearch = true;
                                        },
                                        borderColor: Colors.white,
                                        hintText: TranslationBase.of(context)
                                            .searchMedicineNameHere,
                                        controller: myController,
                                        onSaved: (value) {},
                                        onFieldSubmitted: (value) {
                                          searchMedicine(context, model);
                                        },
                                        inputFormatter: ONLY_LETTERS,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 15.0,
                                  ),
                                  Visibility(
                                    visible: visbiltySearch,
                                    child: Container(
                                      child: Column(
                                        children: [
                                          FractionallySizedBox(
                                            widthFactor: 0.8,
                                            child: Container(
                                              child: Wrap(
                                                alignment: WrapAlignment.center,
                                                children: <Widget>[
                                                  // TODO change it secondary button and add loading
                                                  AppButton(
                                                    title: TranslationBase.of(
                                                            context)
                                                        .search,
                                                    onPressed: () async {
                                                      await searchMedicine(
                                                          context, model);
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          if (myController.text != '')
                                            Container(
                                              height: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.5,
                                              child: ListView.builder(
                                                padding: const EdgeInsets.only(
                                                    top: 20),

                                                scrollDirection: Axis.vertical,
                                                // shrinkWrap: true,
                                                itemCount:
                                                    model.allMedicationList ==
                                                            null
                                                        ? 0
                                                        : model
                                                            .allMedicationList
                                                            .length,
                                                itemBuilder:
                                                    (BuildContext context,
                                                        int index) {
                                                  return InkWell(
                                                    child: MedicineItemWidget(
                                                        label: model
                                                            .allMedicationList[
                                                                index]
                                                            .description
                                                        // url: model
                                                        //         .pharmacyItemsList[
                                                        //     index]["ImageSRCUrl"],
                                                        ),
                                                    onTap: () {
                                                      model.getItem(
                                                          itemID: model
                                                              .allMedicationList[
                                                                  index]
                                                              .itemId);
                                                      visbiltyPrescriptionForm =
                                                          true;
                                                      visbiltySearch = false;
                                                      _selectedMedication =
                                                          model.allMedicationList[
                                                              index];
                                                      uom = _selectedMedication
                                                          .uom;
                                                    },
                                                  );
                                                },
                                              ),
                                            ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: spaceBetweenTextFileds,
                                  ),
                                  Visibility(
                                    visible: visbiltyPrescriptionForm,
                                    child: Container(
                                      child: Column(
                                        children: [
                                          Container(
                                            child: Row(
                                              children: [
                                                AppText(
                                                  'Order Type',
                                                  fontWeight: FontWeight.w600,
                                                ),
                                                Radio(
                                                  activeColor:
                                                      Color(0xFFB9382C),
                                                  value: 1,
                                                  groupValue: selectedType,
                                                  onChanged: (value) {
                                                    setSelectedType(value);
                                                  },
                                                ),
                                                Text('Regular'),
                                              ],
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            width: double.infinity,
                                            child: Row(
                                              children: [
                                                Container(
                                                  width: MediaQuery.of(context)
                                                          .size
                                                          .width *
                                                      0.550,
                                                  child: TextFields(
                                                    inputFormatters: [
                                                      LengthLimitingTextInputFormatter(
                                                          5),
                                                      // WhitelistingTextInputFormatter
                                                      //     .digitsOnly
                                                    ],
                                                    hintText:
                                                        TranslationBase.of(
                                                                context)
                                                            .strength,
                                                    controller:
                                                        strengthController,
                                                    keyboardType: TextInputType
                                                        .numberWithOptions(
                                                      decimal: true,
                                                    ),
                                                    onChanged: (String value) {
                                                      setState(() {
                                                        strengthChar =
                                                            value.length;
                                                      });
                                                      if (strengthChar >= 5) {
                                                        DrAppToastMsg
                                                            .showErrorToast(
                                                                "Only 5 Digits allowed for strength");
                                                      }
                                                    },
                                                    onSubmit: (_) {
                                                      if (_selectedMedication !=
                                                              null &&
                                                          duration != null &&
                                                          frequency != null &&
                                                          strengthController
                                                                  .text !=
                                                              null) {
                                                        model.getBoxQuantity(
                                                            freq: frequency[
                                                                'parameterCode'],
                                                            duration:
                                                                duration['id'],
                                                            itemCode:
                                                                _selectedMedication
                                                                    .itemId,
                                                            strength: double.parse(
                                                                strengthController
                                                                    .text));
                                                        box = model.boxQuintity;

                                                        return;
                                                      }
                                                    },
                                                    // validator: (value) {
                                                    //   if (value.isEmpty &&
                                                    //       strengthController.text.length >
                                                    //           4)
                                                    //     return TranslationBase.of(context)
                                                    //         .emptyMessage;
                                                    //   else
                                                    //     return null;
                                                    // },
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: 10.0,
                                                ),
                                                Container(
                                                  color: Colors.white,
                                                  width: MediaQuery.of(context)
                                                          .size
                                                          .width *
                                                      0.350,
                                                  child: InkWell(
                                                    onTap:
                                                        model.itemMedicineListUnit !=
                                                                null
                                                            ? () {
                                                                Helpers
                                                                    .hideKeyboard(
                                                                        context);
                                                                ListSelectDialog
                                                                    dialog =
                                                                    ListSelectDialog(
                                                                  list: model
                                                                      .itemMedicineListUnit,
                                                                  attributeName:
                                                                      'description',
                                                                  attributeValueId:
                                                                      'parameterCode',
                                                                  okText: TranslationBase.of(
                                                                          context)
                                                                      .ok,
                                                                  okFunction:
                                                                      (selectedValue) {
                                                                    setState(
                                                                        () {
                                                                      units =
                                                                          selectedValue;
                                                                      units['isDefault'] =
                                                                          true;
                                                                    });
                                                                  },
                                                                );
                                                                showDialog(
                                                                  barrierDismissible:
                                                                      false,
                                                                  context:
                                                                      context,
                                                                  builder:
                                                                      (BuildContext
                                                                          context) {
                                                                    return dialog;
                                                                  },
                                                                );
                                                              }
                                                            : null,
                                                    child: TextField(
                                                        decoration:
                                                            textFieldSelectorDecoration(
                                                                'UNIT',
                                                                units != null
                                                                    ? units[
                                                                        'description']
                                                                    : null,
                                                                true),
                                                        enabled: false),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap:
                                                  model.itemMedicineListRoute !=
                                                          null
                                                      ? () {
                                                          Helpers.hideKeyboard(
                                                              context);
                                                          ListSelectDialog
                                                              dialog =
                                                              ListSelectDialog(
                                                            list: model
                                                                .itemMedicineListRoute,
                                                            attributeName:
                                                                'description',
                                                            attributeValueId:
                                                                'parameterCode',
                                                            okText:
                                                                TranslationBase.of(
                                                                        context)
                                                                    .ok,
                                                            okFunction:
                                                                (selectedValue) {
                                                              setState(() {
                                                                route =
                                                                    selectedValue;
                                                                route['isDefault'] =
                                                                    true;
                                                              });
                                                              if (route ==
                                                                  null) {
                                                                Helpers.showErrorToast(
                                                                    'plase fill');
                                                              }
                                                            },
                                                          );
                                                          showDialog(
                                                            barrierDismissible:
                                                                false,
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return dialog;
                                                            },
                                                          );
                                                        }
                                                      : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        TranslationBase.of(
                                                                context)
                                                            .route,
                                                        route != null
                                                            ? route[
                                                                'description']
                                                            : null,
                                                        true),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap:
                                                  model.itemMedicineList != null
                                                      ? () {
                                                          Helpers.hideKeyboard(
                                                              context);
                                                          ListSelectDialog
                                                              dialog =
                                                              ListSelectDialog(
                                                            list: model
                                                                .itemMedicineList,
                                                            attributeName:
                                                                'description',
                                                            attributeValueId:
                                                                'parameterCode',
                                                            okText:
                                                                TranslationBase.of(
                                                                        context)
                                                                    .ok,
                                                            okFunction:
                                                                (selectedValue) {
                                                              setState(() {
                                                                frequency =
                                                                    selectedValue;
                                                                frequency[
                                                                        'isDefault'] =
                                                                    true;
                                                                if (_selectedMedication != null &&
                                                                    duration !=
                                                                        null &&
                                                                    frequency !=
                                                                        null &&
                                                                    strengthController
                                                                            .text !=
                                                                        null) {
                                                                  model.getBoxQuantity(
                                                                      freq: frequency[
                                                                          'parameterCode'],
                                                                      duration:
                                                                          duration[
                                                                              'id'],
                                                                      itemCode:
                                                                          _selectedMedication
                                                                              .itemId,
                                                                      strength:
                                                                          double.parse(
                                                                              strengthController.text));

                                                                  return;
                                                                }
                                                              });
                                                            },
                                                          );
                                                          showDialog(
                                                            barrierDismissible:
                                                                false,
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return dialog;
                                                            },
                                                          );
                                                        }
                                                      : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        TranslationBase.of(
                                                                context)
                                                            .frequency,
                                                        frequency != null
                                                            ? frequency[
                                                                'description']
                                                            : null,
                                                        true),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap:
                                                  model.medicationDoseTimeList !=
                                                          null
                                                      ? () {
                                                          Helpers.hideKeyboard(
                                                              context);
                                                          ListSelectDialog
                                                              dialog =
                                                              ListSelectDialog(
                                                            list: model
                                                                .medicationDoseTimeList,
                                                            attributeName:
                                                                'nameEn',
                                                            attributeValueId:
                                                                'id',
                                                            okText:
                                                                TranslationBase.of(
                                                                        context)
                                                                    .ok,
                                                            okFunction:
                                                                (selectedValue) {
                                                              setState(() {
                                                                doseTime =
                                                                    selectedValue;
                                                              });
                                                            },
                                                          );
                                                          showDialog(
                                                            barrierDismissible:
                                                                false,
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return dialog;
                                                            },
                                                          );
                                                        }
                                                      : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        TranslationBase.of(
                                                                context)
                                                            .doseTime,
                                                        doseTime != null
                                                            ? doseTime['nameEn']
                                                            : null,
                                                        true),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          if (model
                                              .patientAssessmentList.isNotEmpty)
                                            Container(
                                              height: screenSize.height * 0.070,
                                              width: double.infinity,
                                              color: Colors.white,
                                              child: Row(
                                                children: [
                                                  Container(
                                                    width:
                                                        MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.29,
                                                    child: InkWell(
                                                      onTap:
                                                          indicationList != null
                                                              ? () {
                                                                  Helpers.hideKeyboard(
                                                                      context);
                                                                }
                                                              : null,
                                                      child: TextField(
                                                        decoration:
                                                            textFieldSelectorDecoration(
                                                                model
                                                                    .patientAssessmentList[
                                                                        0]
                                                                    .icdCode10ID
                                                                    .toString(),
                                                                indication !=
                                                                        null
                                                                    ? indication[
                                                                        'name']
                                                                    : null,
                                                                false),
                                                        enabled: true,
                                                        readOnly: true,
                                                      ),
                                                    ),
                                                  ),
                                                  Container(
                                                    width:
                                                        MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.65,
                                                    color: Colors.white,
                                                    child: InkWell(
                                                      onTap:
                                                          indicationList != null
                                                              ? () {
                                                                  Helpers.hideKeyboard(
                                                                      context);
                                                                }
                                                              : null,
                                                      child: TextField(
                                                        maxLines: 5,
                                                        decoration:
                                                            textFieldSelectorDecoration(
                                                                model
                                                                    .patientAssessmentList[
                                                                        0]
                                                                    .asciiDesc
                                                                    .toString(),
                                                                indication !=
                                                                        null
                                                                    ? indication[
                                                                        'name']
                                                                    : null,
                                                                false),
                                                        enabled: true,
                                                        readOnly: true,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap: () => selectDate(
                                                  context, widget.model),
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        TranslationBase.of(
                                                                context)
                                                            .date,
                                                        selectedDate != null
                                                            ? "${DateUtils.convertStringToDateFormat(selectedDate.toString(), "yyyy-MM-dd")}"
                                                            : null,
                                                        true,
                                                        suffixIcon: Icon(
                                                          Icons.calendar_today,
                                                          color: Colors.black,
                                                        )),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap:
                                                  model.medicationDurationList !=
                                                          null
                                                      ? () {
                                                          Helpers.hideKeyboard(
                                                              context);
                                                          ListSelectDialog
                                                              dialog =
                                                              ListSelectDialog(
                                                            list: model
                                                                .medicationDurationList,
                                                            attributeName:
                                                                'nameEn',
                                                            attributeValueId:
                                                                'id',
                                                            okText:
                                                                TranslationBase.of(
                                                                        context)
                                                                    .ok,
                                                            okFunction:
                                                                (selectedValue) {
                                                              setState(() {
                                                                duration =
                                                                    selectedValue;
                                                                if (_selectedMedication != null &&
                                                                    duration !=
                                                                        null &&
                                                                    frequency !=
                                                                        null &&
                                                                    strengthController
                                                                            .text !=
                                                                        null) {
                                                                  model
                                                                      .getBoxQuantity(
                                                                    freq: frequency[
                                                                        'parameterCode'],
                                                                    duration:
                                                                        duration[
                                                                            'id'],
                                                                    itemCode:
                                                                        _selectedMedication
                                                                            .itemId,
                                                                    strength: double.parse(
                                                                        strengthController
                                                                            .text),
                                                                  );
                                                                  box = model
                                                                      .boxQuintity;

                                                                  return;
                                                                }
                                                              });
                                                            },
                                                          );
                                                          showDialog(
                                                            barrierDismissible:
                                                                false,
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return dialog;
                                                            },
                                                          );
                                                        }
                                                      : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        TranslationBase.of(
                                                                context)
                                                            .duration,
                                                        duration != null
                                                            ? duration['nameEn']
                                                            : null,
                                                        true),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap: model.allMedicationList !=
                                                      null
                                                  ? () {
                                                      Helpers.hideKeyboard(
                                                          context);
                                                      ListSelectDialog dialog =
                                                          ListSelectDialog(
                                                        list: model
                                                            .allMedicationList,
                                                        attributeName: 'nameEn',
                                                        attributeValueId: 'id',
                                                        okText:
                                                            TranslationBase.of(
                                                                    context)
                                                                .ok,
                                                        okFunction:
                                                            (selectedValue) {
                                                          setState(() {
                                                            duration =
                                                                selectedValue;
                                                          });
                                                        },
                                                      );
                                                      showDialog(
                                                        barrierDismissible:
                                                            false,
                                                        context: context,
                                                        builder: (BuildContext
                                                            context) {
                                                          return dialog;
                                                        },
                                                      );
                                                    }
                                                  : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        "UOM",
                                                        uom != null
                                                            ? uom
                                                            : null,
                                                        false),
                                                //enabled: false,
                                                readOnly: true,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            height: screenSize.height * 0.070,
                                            color: Colors.white,
                                            child: InkWell(
                                              onTap: model.allMedicationList !=
                                                      null
                                                  ? () {
                                                      Helpers.hideKeyboard(
                                                          context);
                                                      ListSelectDialog dialog =
                                                          ListSelectDialog(
                                                        list: model
                                                            .allMedicationList,
                                                        attributeName: 'nameEn',
                                                        attributeValueId: 'id',
                                                        okText:
                                                            TranslationBase.of(
                                                                    context)
                                                                .ok,
                                                        okFunction:
                                                            (selectedValue) {
                                                          setState(() {
                                                            duration =
                                                                selectedValue;
                                                          });
                                                        },
                                                      );
                                                      showDialog(
                                                        barrierDismissible:
                                                            false,
                                                        context: context,
                                                        builder: (BuildContext
                                                            context) {
                                                          return dialog;
                                                        },
                                                      );
                                                    }
                                                  : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        "Box Quantity",
                                                        box != null
                                                            ? "Box Quantity: " +
                                                                model
                                                                    .boxQuintity
                                                                    .toString()
                                                            : null,
                                                        false),
                                                //enabled: false,
                                                readOnly: true,
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(6.0)),
                                                border: Border.all(
                                                    width: 1.0,
                                                    color:
                                                        HexColor("#CCCCCC"))),
                                            child: TextFields(
                                              maxLines: 6,
                                              minLines: 4,
                                              hintText:
                                                  TranslationBase.of(context)
                                                      .instruction,
                                              controller: instructionController,
                                              //keyboardType: TextInputType.number,
                                            ),
                                          ),
                                          SizedBox(
                                              height: spaceBetweenTextFileds),
                                          Container(
                                            margin: EdgeInsets.all(
                                                SizeConfig.widthMultiplier * 5),
                                            child: Wrap(
                                              alignment: WrapAlignment.center,
                                              children: <Widget>[
                                                AppButton(
                                                  color: Color(0xff359846),
                                                  title: TranslationBase.of(
                                                          context)
                                                      .addMedication,
                                                  fontWeight: FontWeight.w600,
                                                  onPressed: () {
                                                    formKey.currentState.save();
                                                    // Navigator.pop(context);
                                                    // openDrugToDrug();
                                                    if (route == null ||
                                                        frequency == null ||
                                                        doseTime == null ||
                                                        duration == null ||
                                                        selectedDate == null ||
                                                        units == null) {
                                                      DrAppToastMsg.showErrorToast(
                                                          "Please Fill All Fields");
                                                      return;
                                                    }
                                                    if (_selectedMedication
                                                            .isNarcotic ==
                                                        true) {
                                                      DrAppToastMsg.showErrorToast(
                                                          "Narcotic medicine can only be prescribed from VIDA");
                                                      Navigator.pop(context);
                                                      return;
                                                    }

                                                    if (double.parse(
                                                            strengthController
                                                                .text) >
                                                        1000.0) {
                                                      DrAppToastMsg.showErrorToast(
                                                          "1000 is the MAX for the strength");
                                                      return;
                                                    }
                                                    if (double.parse(
                                                            strengthController
                                                                .text) <
                                                        0.0) {
                                                      DrAppToastMsg.showErrorToast(
                                                          "strength can't be zero");
                                                      return;
                                                    }

                                                    if (formKey.currentState
                                                        .validate()) {
                                                      Navigator.pop(context);
                                                      openDrugToDrug(model);
                                                      {
                                                        // postProcedure(
                                                        //   icdCode: model
                                                        //           .patientAssessmentList
                                                        //           .isNotEmpty
                                                        //       ? model
                                                        //               .patientAssessmentList[
                                                        //                   0]
                                                        //               .icdCode10ID
                                                        //               .isEmpty
                                                        //           ? "test"
                                                        //           : model
                                                        //               .patientAssessmentList[
                                                        //                   0]
                                                        //               .icdCode10ID
                                                        //               .toString()
                                                        //       : "test",
                                                        //   // icdCode: model
                                                        //   //     .patientAssessmentList
                                                        //   //     .map((value) => value
                                                        //   //         .icdCode10ID
                                                        //   //         .trim())
                                                        //   //     .toList()
                                                        //   //     .join(' '),
                                                        //   dose:
                                                        //       strengthController
                                                        //           .text,
                                                        //   doseUnit: units[
                                                        //           'parameterCode']
                                                        //       .toString(),
                                                        //   patient:
                                                        //       widget.patient,
                                                        //   doseTimeIn:
                                                        //       doseTime['id']
                                                        //           .toString(),
                                                        //   model: widget.model,
                                                        //   duration:
                                                        //       duration['id']
                                                        //           .toString(),
                                                        //   frequency: frequency[
                                                        //           'parameterCode']
                                                        //       .toString(),
                                                        //   route: route[
                                                        //           'parameterCode']
                                                        //       .toString(),
                                                        //   drugId:
                                                        //       _selectedMedication
                                                        //           .itemId
                                                        //           .toString(),
                                                        //   strength:
                                                        //       strengthController
                                                        //           .text,
                                                        //   indication:
                                                        //       indicationController
                                                        //           .text,
                                                        //   instruction:
                                                        //       instructionController
                                                        //           .text,
                                                        //   doseTime:
                                                        //       selectedDate,
                                                        // );
                                                      }
                                                    }

                                                    {
                                                      // Navigator.push(
                                                      //   context,
                                                      //   MaterialPageRoute(
                                                      //       builder: (context) =>
                                                      //           NewPrescriptionScreen()),
                                                      // );
                                                    }
                                                  },
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }),
        ),
      ),
    );
  }

  selectDate(BuildContext context, PrescriptionViewModel model) async {
    Helpers.hideKeyboard(context);
    DateTime selectedDate;
    selectedDate = DateTime.now();
    final DateTime picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime.now(),
      lastDate: DateTime(2040),
      initialEntryMode: DatePickerEntryMode.calendar,
    );
    if (picked != null && picked != selectedDate) {
      setState(() {
        this.selectedDate = picked;
      });
    }
  }

  InputDecoration textFieldSelectorDecoration(
      String hintText, String selectedText, bool isDropDown,
      {Icon suffixIcon}) {
    return InputDecoration(
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFEFEFEF), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFEFEFEF), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown
          ? suffixIcon != null
              ? suffixIcon
              : Icon(
                  Icons.keyboard_arrow_down_sharp,
                  color: Color(0xff2E303A),
                )
          : null,
      hintStyle: TextStyle(
        fontSize: 13,
        color: Color(0xff2E303A),
        fontFamily: 'Poppins',
        fontWeight: FontWeight.w600,
      ),
      labelText: selectedText != null ? '$hintText\n$selectedText' : null,
      labelStyle: TextStyle(
        fontSize: 13,
        color: Color(0xff2E303A),
        fontFamily: 'Poppins',
        fontWeight: FontWeight.w600,
      ),
    );
  }

  openDrugToDrug(model) {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
            height: SizeConfig.realScreenHeight * .8,
            width: SizeConfig.realScreenWidth,
            child: SingleChildScrollView(
                child: Column(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                DrugToDrug(
                    widget.patient,
                    getPriscriptionforDrug(widget.prescriptionList),
                    model.patientAssessmentList),
                Container(
                    margin: EdgeInsets.all(SizeConfig.widthMultiplier * 3),
                    child: AppButton(
                      title: TranslationBase.of(context).addMedication,
                      onPressed: () {
                        Navigator.pop(context);

                        postProcedure(
                          icdCode: model.patientAssessmentList.isNotEmpty
                              ? model.patientAssessmentList[0].icdCode10ID
                                      .isEmpty
                                  ? "test"
                                  : model.patientAssessmentList[0].icdCode10ID
                                      .toString()
                              : "test",
                          // icdCode: model
                          //     .patientAssessmentList
                          //     .map((value) => value
                          //         .icdCode10ID
                          //         .trim())
                          //     .toList()
                          //     .join(' '),
                          dose: strengthController.text,
                          doseUnit: units['parameterCode'].toString(),
                          patient: widget.patient,
                          doseTimeIn: doseTime['id'].toString(),
                          model: widget.model,
                          duration: duration['id'].toString(),
                          frequency: frequency['parameterCode'].toString(),
                          route: route['parameterCode'].toString(),
                          drugId: _selectedMedication.itemId.toString(),
                          strength: strengthController.text,
                          indication: indicationController.text,
                          instruction: instructionController.text,
                          doseTime: selectedDate,
                        );

                        // postProcedure(
                        //   icdCode: model.patientAssessmentList.isNotEmpty
                        //       ? model.patientAssessmentList[0].icdCode10ID
                        //               .isEmpty
                        //           ? "test"
                        //           : model.patientAssessmentList[0].icdCode10ID
                        //               .toString()
                        //       : "test",
                        //   // icdCode: model
                        //   //     .patientAssessmentList
                        //   //     .map((value) => value
                        //   //         .icdCode10ID
                        //   //         .trim())
                        //   //     .toList()
                        //   //     .join(' '),
                        //   dose: strengthController.text,
                        //   doseUnit: units['parameterCode'].toString(),
                        //   patient: widget.patient,
                        //   doseTimeIn: doseTime['id'].toString(),
                        //   model: widget.model,
                        //   duration: duration['id'].toString(),
                        //   frequency: frequency['parameterCode'].toString(),
                        //   route: route['parameterCode'].toString(),
                        //   drugId: _selectedMedication.itemId.toString(),
                        //   strength: strengthController.text,
                        //   indication: indicationController.text,
                        //   instruction: instructionController.text,
                        //   doseTime: selectedDate,
                        // );
                      },
                    ))
              ],
            )),

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

  getPriscriptionforDrug(List<PrescriptionModel> prescriptionList) {
    var prescriptionDetails = [];
    if (prescriptionList.length > 0) {
      prescriptionList[0].entityList.forEach((element) {
        if (element.mediSpanGPICode != null) {
          prescriptionDetails.add({
            'DrugId': element.mediSpanGPICode,
            'DrugName': element.medicationName,
            'Dose': element.doseDailyQuantity,
            'DoseType': element.doseDailyUnitID,
            'Unit': element.uom,
            'FrequencyType': element.frequencyID,
            'Duration': element.doseDurationDays,
            'RouteID': element.routeID,
            'IsScreen': element.isSIG
          });
        }
      });
    }
    if (_selectedMedication.mediSpanGPICode != null) {
      prescriptionDetails.add({
        'DrugId': _selectedMedication.mediSpanGPICode,
        'DrugName': _selectedMedication.description,
        'Dose': strengthController.text,
        'DoseType': units['parameterCode'].toString(),
        'Unit': units['description'],
        'FrequencyType': frequency['parameterCode'].toString(),
        'Duration': duration['id'].toString(),
        'RouteID': route['parameterCode'].toString(),
        'IsScreen': true
      });
    }
    return prescriptionDetails;
  }

  searchMedicine(context, MedicineViewModel model) async {
    FocusScope.of(context).unfocus();
    // if (myController.text.isEmpty()) {
    //   Helpers.showErrorToast(TranslationBase.of(context).typeMedicineName);
    //   //"Type Medicine Name")
    //   return;
    // }
    if (myController.text.length < 3) {
      Helpers.showErrorToast(TranslationBase.of(context).moreThan3Letter);
      return;
    }

    //GifLoaderDialogUtils.showMyDialog(context);

    await model.getMedicationList(drug: myController.text);
    //GifLoaderDialogUtils.hideDialog(context);
  }
}
