import 'package:autocomplete_textfield/autocomplete_textfield.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/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/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.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/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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';

class UpdatePrescriptionForm extends StatefulWidget {
  final String drugName;
  final String doseStreangth;
  final int drugId;
  final String remarks;
  final PatiantInformtion patient;
  final String duration;
  final String route;
  final String dose;
  final String doseUnit;
  final String enteredRemarks;
  final String startDate;
  final String frequency;
  final String drugNameGeneric;
  final String uom;
  final int box;

  final PrescriptionViewModel model;

  UpdatePrescriptionForm(
      {this.drugName,
      this.doseStreangth,
      this.drugId,
      this.remarks,
      this.patient,
      this.duration,
      this.route,
      this.dose,
      this.startDate,
      this.doseUnit,
      this.enteredRemarks,
      this.frequency,
      this.model,
      this.drugNameGeneric,
      this.uom,
      this.box});
  @override
  _UpdatePrescriptionFormState createState() => _UpdatePrescriptionFormState();
}

class _UpdatePrescriptionFormState extends State<UpdatePrescriptionForm> {
  TextEditingController strengthController = TextEditingController();
  TextEditingController remarksController = TextEditingController();
  int testNum = 0;
  int strengthChar;
  PatiantInformtion patient;
  dynamic route;
  dynamic doseTime;
  dynamic frequencyUpdate;
  dynamic updatedDuration;
  dynamic units;
  GetMedicationResponseModel newSelectedMedication;
  GlobalKey key =
      new GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>>();
  List<dynamic> indicationList;
  dynamic indication;
  DateTime selectedDate;
  @override
  void initState() {
    super.initState();
    strengthController.text = widget.doseStreangth;
    remarksController.text = widget.remarks;
    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);
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return StatefulBuilder(builder:
        (BuildContext context, StateSetter setState /*You can rename this!*/) {
      return BaseView<MedicineViewModel>(
        onModelReady: (model) async {
          await model.getMedicationList();
          await model.getMedicationStrength();
          await model.getMedicationDuration();
          await model.getMedicationRoute();
          await model.getMedicationFrequency();
          await model.getMedicationDoseTime();
          await model.getItem(itemID: widget.drugId);
          //await model.getMedicationIndications();
          route = model.getLookupByIdFilter(
              model.itemMedicineListRoute, widget.route);
          doseTime =
              model.getLookupById(model.medicationDoseTimeList, widget.dose);
          updatedDuration = model.getLookupById(
              model.medicationDurationList, widget.duration);
          units = model.getLookupByIdFilter(
              model.itemMedicineListUnit, widget.doseUnit);
          frequencyUpdate = model.getLookupById(
              model.medicationFrequencyList, widget.frequency);
        },
        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.99,
                minChildSize: 0.6,
                builder:
                    (BuildContext context, ScrollController scrollController) {
                  return SingleChildScrollView(
                    child: Container(
                        height: MediaQuery.of(context).size.height * 1.5,
                        child: Form(
                          child: Padding(
                            padding: EdgeInsets.symmetric(
                                horizontal: 20.0, vertical: 12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                AppText(
                                  widget.drugName.toUpperCase(),
                                  fontWeight: FontWeight.w900,
                                ),
                                SizedBox(
                                  height: 10.0,
                                ),
                                Column(
                                  children: [
                                    // Container(
                                    //   height: MediaQuery.of(context).size.height *
                                    //       0.070,
                                    //   child: InkWell(
                                    //     onTap: model.allMedicationList != null
                                    //         ? () {
                                    //             setState(() {
                                    //               newSelectedMedication = null;
                                    //             });
                                    //           }
                                    //         : null,
                                    //     child: newSelectedMedication == null
                                    //         ? AutoCompleteTextField<
                                    //             GetMedicationResponseModel>(
                                    //             decoration:
                                    //                 textFieldSelectorDecoration(
                                    //               widget.drugNameGeneric,
                                    //               newSelectedMedication != null
                                    //                   ? newSelectedMedication
                                    //                       .genericName
                                    //                   : null,
                                    //               true,
                                    //             ),
                                    //             itemSubmitted: (item) => setState(
                                    //                 () => newSelectedMedication =
                                    //                     item),
                                    //             key: key,
                                    //             suggestions:
                                    //                 model.allMedicationList,
                                    //             itemBuilder: (context,
                                    //                     suggestion) =>
                                    //                 new Padding(
                                    //                     child: AppText(suggestion
                                    //                             .description +
                                    //                         '/' +
                                    //                         suggestion.genericName),
                                    //                     padding:
                                    //                         EdgeInsets.all(8.0)),
                                    //             itemSorter: (a, b) => 1,
                                    //             itemFilter: (suggestion, input) =>
                                    //                 suggestion.genericName
                                    //                     .toLowerCase()
                                    //                     .startsWith(
                                    //                         input.toLowerCase()) ||
                                    //                 suggestion.description
                                    //                     .toLowerCase()
                                    //                     .startsWith(
                                    //                         input.toLowerCase()) ||
                                    //                 suggestion.keywords
                                    //                     .toLowerCase()
                                    //                     .startsWith(
                                    //                         input.toLowerCase()),
                                    //           )
                                    //         : TextField(
                                    //             decoration:
                                    //                 textFieldSelectorDecoration(
                                    //               TranslationBase.of(context)
                                    //                   .searchMedicineNameHere,
                                    //               newSelectedMedication != null
                                    //                   ? newSelectedMedication
                                    //                           .description +
                                    //                       ('${newSelectedMedication.genericName}')
                                    //                   : null,
                                    //               true,
                                    //             ),
                                    //             enabled: false,
                                    //           ),
                                    //   ),
                                    // ),
                                    // SizedBox(
                                    //   height: 12,
                                    // ),
                                    Container(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.060,
                                      width: double.infinity,
                                      child: Row(
                                        children: [
                                          Container(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                0.4900,
                                            height: MediaQuery.of(context)
                                                    .size
                                                    .height *
                                                0.55,
                                            child: TextFields(
                                              inputFormatters: [
                                                LengthLimitingTextInputFormatter(
                                                    5),
                                                // WhitelistingTextInputFormatter
                                                //     .digitsOnly
                                              ],

                                              hintText: widget.doseStreangth,
                                              fontSize: 15.0,
                                              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");
                                                }
                                              },
                                              // validator: (value) {
                                              //   if (value.isEmpty &&
                                              //       strengthController.text.length >
                                              //           4)
                                              //     return TranslationBase.of(context)
                                              //         .emptyMessage;
                                              //   else
                                              //     return null;
                                              // },
                                            ),
                                          ),
                                          SizedBox(
                                            width: 10.0,
                                          ),
                                          Container(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                0.3700,
                                            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;
                                                              });
                                                            },
                                                          );
                                                          showDialog(
                                                            barrierDismissible:
                                                                false,
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return dialog;
                                                            },
                                                          );
                                                        }
                                                      : null,
                                              child: TextField(
                                                decoration:
                                                    textFieldSelectorDecoration(
                                                        'UNIT Type',
                                                        units != null
                                                            ? units[
                                                                'description']
                                                            : null,
                                                        true),
                                                enabled: false,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12,
                                    ),
                                    Container(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.070,
                                      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;
                                                    });
                                                    if (route == null) {
                                                      route = route['id'];
                                                    }
                                                  },
                                                );
                                                showDialog(
                                                  barrierDismissible: false,
                                                  context: context,
                                                  builder:
                                                      (BuildContext context) {
                                                    return dialog;
                                                  },
                                                );
                                              }
                                            : null,
                                        child: TextField(
                                          decoration:
                                              textFieldSelectorDecoration(
                                                  'Route',
                                                  route != null
                                                      ? route['description']
                                                      : null,
                                                  true),
                                          enabled: false,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.070,
                                      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: 12.0,
                                    ),
                                    Container(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.070,
                                      child: InkWell(
                                        onTap: model.medicationFrequencyList !=
                                                null
                                            ? () {
                                                Helpers.hideKeyboard(context);
                                                ListSelectDialog dialog =
                                                    ListSelectDialog(
                                                  list: model
                                                      .medicationFrequencyList,
                                                  attributeName: 'nameEn',
                                                  attributeValueId: 'id',
                                                  okText: TranslationBase.of(
                                                          context)
                                                      .ok,
                                                  okFunction: (selectedValue) {
                                                    setState(() {
                                                      frequencyUpdate =
                                                          selectedValue;
                                                    });
                                                  },
                                                );
                                                showDialog(
                                                  barrierDismissible: false,
                                                  context: context,
                                                  builder:
                                                      (BuildContext context) {
                                                    return dialog;
                                                  },
                                                );
                                              }
                                            : null,
                                        child: TextField(
                                          decoration:
                                              textFieldSelectorDecoration(
                                                  TranslationBase.of(context)
                                                      .frequency,
                                                  frequencyUpdate != null
                                                      ? frequencyUpdate[
                                                          'nameEn']
                                                      : null,
                                                  true),
                                          enabled: false,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.070,
                                      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(() {
                                                      updatedDuration =
                                                          selectedValue;
                                                    });
                                                  },
                                                );
                                                showDialog(
                                                  barrierDismissible: false,
                                                  context: context,
                                                  builder:
                                                      (BuildContext context) {
                                                    return dialog;
                                                  },
                                                );
                                              }
                                            : null,
                                        child: TextField(
                                          decoration:
                                              textFieldSelectorDecoration(
                                                  TranslationBase.of(context)
                                                      .duration,
                                                  updatedDuration != null
                                                      ? updatedDuration[
                                                              'nameEn']
                                                          .toString()
                                                      : null,
                                                  true),
                                          enabled: false,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                        height: model.patientAssessmentList
                                                .isNotEmpty
                                            ? screenSize.height * 0.070
                                            : 0.0,
                                        width: model.patientAssessmentList
                                                .isNotEmpty
                                            ? double.infinity
                                            : 0.0,
                                        child: model.patientAssessmentList
                                                .isNotEmpty
                                            ? 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
                                                                    .isNotEmpty
                                                                ? model
                                                                    .patientAssessmentList[
                                                                        0]
                                                                    .icdCode10ID
                                                                    .toString()
                                                                : '',
                                                            indication != null
                                                                ? indication[
                                                                    'name']
                                                                : null,
                                                            true),
                                                        enabled: true,
                                                        readOnly: true,
                                                      ),
                                                    ),
                                                  ),
                                                  Container(
                                                    width:
                                                        MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.61,
                                                    child: InkWell(
                                                      onTap:
                                                          indicationList != null
                                                              ? () {
                                                                  Helpers.hideKeyboard(
                                                                      context);
                                                                }
                                                              : null,
                                                      child: TextField(
                                                        maxLines: 3,
                                                        decoration: textFieldSelectorDecoration(
                                                            model.patientAssessmentList
                                                                    .isNotEmpty
                                                                ? model
                                                                    .patientAssessmentList[
                                                                        0]
                                                                    .asciiDesc
                                                                    .toString()
                                                                : '',
                                                            indication != null
                                                                ? indication[
                                                                    'name']
                                                                : null,
                                                            true),
                                                        enabled: true,
                                                        readOnly: true,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              )
                                            : null),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                      height: screenSize.height * 0.070,
                                      child: InkWell(
                                        onTap: () =>
                                            selectDate(context, widget.model),
                                        child: TextField(
                                          decoration: Helpers
                                              .textFieldSelectorDecoration(
                                              DateUtils.getDateFormatted(
                                                      DateTime.parse(
                                                          widget.startDate)),
                                                  selectedDate != null
                                                      ? "${DateUtils.convertStringToDateFormat(selectedDate.toString(), "yyyy-MM-dd")}"
                                                      : null,
                                                  true,
                                                  suffixIcon: Icon(
                                                    Icons.calendar_today,
                                                    color: Colors.black,
                                                  )),
                                          enabled: false,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                      height: screenSize.height * 0.070,
                                      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",
                                                  widget.uom != null
                                                      ? widget.uom
                                                      : null,
                                                  true),
                                          // enabled: false,
                                          readOnly: true,
                                        ),
                                      ),
                                    ),
                                    Container(
                                      height: screenSize.height * 0.070,
                                      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',
                                                  widget.box != null
                                                      ? "Box Quantity: " +
                                                          widget.box.toString()
                                                      : null,
                                                  true),
                                          // enabled: false,
                                          readOnly: true,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 12.0,
                                    ),
                                    Container(
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(6.0)),
                                          border: Border.all(
                                              width: 1.0,
                                              color: HexColor("#CCCCCC"))),
                                      child: TextFields(
                                        controller: remarksController,
                                        maxLines: 7,
                                        minLines: 4,
                                      ),
                                    ),
                                    SizedBox(
                                      height: 10.0,
                                    ),
                                    SizedBox(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.08,
                                    ),
                                    Container(
                                      margin: EdgeInsets.all(
                                          SizeConfig.widthMultiplier * 2),
                                      child: Wrap(
                                        alignment: WrapAlignment.center,
                                        children: <Widget>[
                                          AppButton(
                                            title: 'update prescription'
                                                .toUpperCase(),
                                            onPressed: () {
                                              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 (strengthController
                                                      .text.length >
                                                  4) {
                                                DrAppToastMsg.showErrorToast(
                                                    "strength can't be more then 4 digits ");
                                                return;
                                              }
                                              // if(units==null&& updatedDuration==null&&frequencyUpdate==null&&)
                                              updatePrescription(
                                                  newStartDate: selectedDate,
                                                  newDoseStreangth:
                                                      strengthController
                                                              .text.isNotEmpty
                                                          ? strengthController
                                                              .text
                                                          : widget
                                                              .doseStreangth,
                                                  newUnit: units != null
                                                      ? units['parameterCode']
                                                          .toString()
                                                      : widget.doseUnit,
                                                  doseUnit: widget.doseUnit,
                                                  doseStreangth:
                                                      widget.doseStreangth,
                                                  duration: widget.duration,
                                                  startDate: widget.startDate,
                                                  doseId: widget.dose,
                                                  frequencyId: widget.frequency,
                                                  routeId: widget.route,
                                                  patient: widget.patient,
                                                  model: widget.model,
                                                  newDuration:
                                                      updatedDuration != null
                                                          ? updatedDuration['id']
                                                              .toString()
                                                          : widget.duration,
                                                  drugId: widget.drugId,
                                                  remarks: remarksController
                                                      .text,
                                                  route: route != null
                                                      ? route['parameterCode']
                                                          .toString()
                                                      : widget.route,
                                                  frequency:
                                                      frequencyUpdate != null
                                                          ? frequencyUpdate[
                                                                  'id']
                                                              .toString()
                                                          : widget.frequency,
                                                  dose: doseTime != null
                                                      ? doseTime['id']
                                                          .toString()
                                                      : widget.dose,
                                                  enteredRemarks:
                                                      widget.enteredRemarks);
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        )),
                  );
                }),
          ),
        ),
      );
    });
  }

  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(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFCCCCCC), width: 2.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown
          ? suffixIcon != null
              ? suffixIcon
              : Icon(
                  Icons.arrow_drop_down,
                  color: Colors.black,
                )
          : null,
      hintStyle: TextStyle(
        fontSize: 14,
        color: Colors.grey.shade600,
      ),
    );
  }

  updatePrescription(
      {PrescriptionViewModel model,
      int drugId,
      String newDrugId,
      String frequencyId,
      String remarks,
      String dose,
      String doseId,
      String frequency,
      String route,
      String routeId,
      String startDate,
      DateTime newStartDate,
      String doseUnit,
      String doseStreangth,
      String newDoseStreangth,
      String duration,
      String newDuration,
      String newUnit,
      String enteredRemarks,
      PatiantInformtion patient}) async {
    //PrescriptionViewModel model = PrescriptionViewModel();
    PostPrescriptionReqModel updatePrescriptionReqModel =
        new PostPrescriptionReqModel();
    List<PrescriptionRequestModel> sss = List();

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

    sss.add(PrescriptionRequestModel(
        covered: true,
        dose: newDoseStreangth.isNotEmpty
            ? double.parse(newDoseStreangth)
            : double.parse(doseStreangth),
        //frequency.isNotEmpty ? int.parse(dose) : 1,
        itemId: drugId,
        doseUnitId:
            newUnit.isNotEmpty ? int.parse(newUnit) : int.parse(doseUnit),
        route: route.isNotEmpty ? int.parse(route) : int.parse(routeId),
        frequency: frequency.isNotEmpty
            ? int.parse(frequency)
            : int.parse(frequencyId),
        remarks: remarks.isEmpty ? enteredRemarks : remarks,
        approvalRequired: true,
        icdcode10Id: "test2",
        doseTime: dose.isNotEmpty ? int.parse(dose) : int.parse(doseId),
        duration: newDuration.isNotEmpty
            ? int.parse(newDuration)
            : int.parse(duration),
        doseStartDate:
            newStartDate != null ? newStartDate.toIso8601String() : startDate));
    updatePrescriptionReqModel.prescriptionRequestModel = sss;
    //postProcedureReqModel.procedures = controlsProcedure;

    await model.updatePrescription(
        updatePrescriptionReqModel, patient.patientMRN);

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

void updatePrescriptionForm(
    {context,
    String drugName,
    String drugNameGeneric,
    int drugId,
    String remarks,
    PrescriptionViewModel model,
    PatiantInformtion patient,
    String rouat,
    String frequency,
    String dose,
    String duration,
    String doseStreangth,
    String doseUnit,
    String enteredRemarks,
    String uom,
    int box,
    String startDate}) {
  TextEditingController remarksController = TextEditingController();
  TextEditingController doseController = TextEditingController();
  TextEditingController frequencyController = TextEditingController();
  TextEditingController routeController = TextEditingController();
  showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return UpdatePrescriptionForm(
          box: box,
          uom: uom,
          drugName: drugName,
          patient: patient,
          doseStreangth: doseStreangth,
          remarks: remarks,
          drugId: drugId,
          enteredRemarks: enteredRemarks,
          duration: duration,
          dose: dose,
          doseUnit: doseUnit,
          frequency: frequency,
          route: rouat,
          startDate: startDate,
          model: model,
          drugNameGeneric: drugNameGeneric,
        );
      });
}
