import 'package:doctor_app_flutter/client/base_app_client.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/my_selected_allergy.dart';
import 'package:doctor_app_flutter/models/SOAP/post_allergy_request_model.dart';
import 'package:doctor_app_flutter/models/SOAP/post_chief_complaint_request_model.dart';
import 'package:doctor_app_flutter/models/SOAP/post_histories_request_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/SOAP/subjective/add_allergies_widget.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/SOAP/subjective/add_history_widget.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/SOAP/subjective/add_medication_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/Text.dart';
import 'package:doctor_app_flutter/widgets/shared/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/expandable-widget-header-body.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class SubjectivePage extends StatefulWidget {
  final Function changePageViewIndex;
  final List<MySelectedAllergy> myAllergiesList;
  final List<MasterKeyModel> myHistoryList ;

  SubjectivePage({Key key, this.changePageViewIndex, this.myAllergiesList, this.myHistoryList});

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

class _SubjectivePageState extends State<SubjectivePage> {
  bool isChiefExpand = false;
  bool isHistoryExpand = false;
  bool isAllergiesExpand = false;
  TextEditingController illnessController = TextEditingController();
  TextEditingController complaintsController = TextEditingController();
  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
      // onModelReady: (model) => model.getMasterLookup(MasterKeysService.Allergies),
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: false,
        baseViewModel: model,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Center(
            child: FractionallySizedBox(
              widthFactor: 0.9,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 30,
                  ),
                  HeaderBodyExpandableNotifier(
                    headerWidget: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Texts('CHIEF COMPLAINTS',
                                variant: isChiefExpand ? "bodyText" : '',
                                bold: isChiefExpand ? true : false,
                                color: Colors.black),
                            Icon(
                              FontAwesomeIcons.asterisk,
                              color: AppGlobal.appPrimaryColor,
                              size: 12,
                            )
                          ],
                        ),
                        InkWell(
                            onTap: () {
                              setState(() {
                                isChiefExpand = !isChiefExpand;
                              });
                            },
                            child: Icon(
                                isChiefExpand ? EvaIcons.minus : EvaIcons.plus))
                      ],
                    ),
                    bodyWidget: Form(
                      key: formKey,
                      child: Column(children: [
                        SizedBox(
                          height: 20,
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 10, right: 10, top: 15),
                          child: TextFields(
                              hintText: "Add Chief Complaints",
                              fontSize: 13.5,
                              // hintColor: Colors.black,
                              fontWeight: FontWeight.w600,
                              maxLines: 25,
                              minLines: 13,
                              controller: complaintsController,
                              validator: (value) {
                                if (value == null || value =="")
                                  return TranslationBase
                                      .of(context)
                                      .emptyMessage;
                                else if (value.length < 25)
                                  return TranslationBase
                                      .of(context)
                                      .chiefComplaintLength;
                                    //"";
                                else
                                  return null;
                              }),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 10, right: 10, top: 15),
                          child: TextFields(
                              hintText: "History of Present Illness",
                              fontSize: 13.5,
                              // hintColor: Colors.black,
                              fontWeight: FontWeight.w600,
                              maxLines: 25,
                              minLines: 13,
                              controller: illnessController,
                              validator: (value) {
                                if (value == null || value =="")
                                  return TranslationBase
                                      .of(context)
                                      .emptyMessage;
                                else
                                  return null;
                              }),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        AddMedication(),
                      ]),
                    ),
                    isExpand: isChiefExpand,
                  ),

                  SizedBox(
                    height: 30,
                  ),
                  Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xffCCCCCC),
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  HeaderBodyExpandableNotifier(
                    headerWidget: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Texts('History'.toUpperCase(),
                                variant: isHistoryExpand ? "bodyText" : '',
                                bold: isHistoryExpand ? true : false,
                                color: Colors.black),
                            Icon(
                              FontAwesomeIcons.asterisk,
                              color: AppGlobal.appPrimaryColor,
                              size: 12,
                            )
                          ],
                        ),
                        InkWell(
                            onTap: () {
                              setState(() {
                                isHistoryExpand = !isHistoryExpand;
                              });
                            },
                            child: Icon(isHistoryExpand
                                ? EvaIcons.minus
                                : EvaIcons.plus))
                      ],
                    ),
                    bodyWidget: Column(
                      children: [
                        AddHistoryWidget(myHistoryList: widget.myHistoryList)
                      ],
                    ),
                    isExpand: isHistoryExpand,
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xffCCCCCC),
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  HeaderBodyExpandableNotifier(
                    headerWidget: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Texts('Allergies'.toUpperCase(),
                                variant: isAllergiesExpand ? "bodyText" : '',
                                bold: isAllergiesExpand ? true : false,
                                color: Colors.black),
                            Icon(
                              FontAwesomeIcons.asterisk,
                              color: AppGlobal.appPrimaryColor,
                              size: 12,
                            )
                          ],
                        ),
                        InkWell(
                            onTap: () {
                              setState(() {
                                isAllergiesExpand = !isAllergiesExpand;
                              });
                            },
                            child: Icon(isAllergiesExpand
                                ? EvaIcons.minus
                                : EvaIcons.plus))
                      ],
                    ),
                    bodyWidget:Column(
                      children: [
                        AddAllergiesWidget(myAllergiesList: widget.myAllergiesList,),
                        SizedBox(
                          height: 30,
                        ),
                      ],
                    )
                    ,
                    isExpand: isAllergiesExpand,
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  Container(
                    width: double.infinity,
                    height: 1,
                    color: Color(0xffCCCCCC),
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  AppButton(
                    title: TranslationBase.of(context).next,
                    loading: model.state == ViewState.BusyLocal,
                    onPressed: () async {
                      addSubjectiveInfo(
                          model: model,
                          myAllergiesList: widget.myAllergiesList,
                          myHistoryList: widget.myHistoryList);
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  addSubjectiveInfo(
      {SOAPViewModel model,
      List<MySelectedAllergy> myAllergiesList,
      List<MasterKeyModel> myHistoryList}) async {
    await postChiefComplaint(model: model);
    if (myHistoryList.length != 0)
      await postHistories(model: model, myHistoryList: myHistoryList);
    if (myAllergiesList.length != 0)
      await postAllergy(myAllergiesList: myAllergiesList, model: model);

    widget.changePageViewIndex(1);
  }

  postAllergy(
      {List<MySelectedAllergy> myAllergiesList, SOAPViewModel model}) async {
    PostAllergyRequestModel postAllergyRequestModel =
        new PostAllergyRequestModel();
    widget.myAllergiesList.forEach((allergy) {
      if (postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM ==
          null)
        postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM = [];
      //TODO: make static value dynamic
      postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM
          .add(ListHisProgNotePatientAllergyDiseaseVM(
              allergyDiseaseId: allergy.selectedAllergy.id,
              allergyDiseaseType: allergy.selectedAllergy.typeId,
              patientMRN: 3120690,
              episodeId: 200012117,
              appointmentNo: 2016054573,
              severity: allergy.selectedAllergySeverity.id,
              remarks: allergy.remark,
              createdBy: 1485,
              //
              createdOn: "2020-08-14T20:37:22.780Z",
              editedBy: 1485,
              editedOn: "2020-08-14T20:37:22.780Z",
              isChecked: false,
              isUpdatedByNurse: false));
    });
    await model.postAllergy(postAllergyRequestModel);

    if (model.state == ViewState.ErrorLocal) {
      helpers.showErrorToast(model.error);
    }
  }

  postHistories(
      {List<MasterKeyModel> myHistoryList, SOAPViewModel model}) async {
    PostHistoriesRequestModel postHistoriesRequestModel =
        new PostHistoriesRequestModel();
    widget.myHistoryList.forEach((history) {
      if (postHistoriesRequestModel.listMedicalHistoryVM == null)
        postHistoriesRequestModel.listMedicalHistoryVM = [];
      //TODO: make static value dynamic
      postHistoriesRequestModel.listMedicalHistoryVM.add(ListMedicalHistoryVM(
        patientMRN: 3120690,
        episodeId: 200012117,
        appointmentNo: 2016054573,
        remarks: "",
        historyId: history.id,
        historyType: history.typeId,
        isChecked: false,
      ));
    });
    await model.postHistories(postHistoriesRequestModel);

    if (model.state == ViewState.ErrorLocal) {
      helpers.showErrorToast(model.error);
    }
  }

  postChiefComplaint({SOAPViewModel model}) async {
    formKey.currentState.save();
    if(formKey.currentState.validate()){
      PostChiefComplaintRequestModel postChiefComplaintRequestModel =
      //TODO: make static value dynamic
      new PostChiefComplaintRequestModel(
          patientMRN: 3120690,
          episodeID: 200012117,
          appointmentNo: 2016054573,
          chiefComplaint: complaintsController.text,
          currentMedication: "currentMedication",
          hopi: illnessController.text,
          isLactation: false,
          ispregnant: false,
          numberOfWeeks: 22);

      await model.postChiefComplaint(postChiefComplaintRequestModel);

      if (model.state == ViewState.ErrorLocal) {
        helpers.showErrorToast(model.error);
      }
    }

  }
}
