import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.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/ChiefComplaint/GetChiefComplaintReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/GeneralGetReqForSOAP.dart';
import 'package:doctor_app_flutter/models/SOAP/GetHistoryReqModel.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/my_selected_history.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/models/doctor/doctor_profile_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/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../shared_soap_widgets/SOAP_step_header.dart';
import '../shared_soap_widgets/expandable_SOAP_widget.dart';
import 'allergies/update_allergies_widget.dart';
import 'cheif_complaints/update_Chief_complaints.dart';
import 'history/update_history_widget.dart';

class UpdateSubjectivePage extends StatefulWidget {
  final Function changePageViewIndex;
  final Function changeLoadingState;
  final List<MySelectedAllergy> myAllergiesList;
  final List<MySelectedHistory> myHistoryList;
  final PatiantInformtion patientInfo;
  final int  currentIndex;

  UpdateSubjectivePage(
      {Key key,
      this.changePageViewIndex,
      this.myAllergiesList,
      this.myHistoryList,
      this.patientInfo, this.changeLoadingState, this.currentIndex});

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

class _UpdateSubjectivePageState extends State<UpdateSubjectivePage> {
  bool isChiefExpand = false;
  bool isHistoryExpand = false;
  bool isAllergiesExpand = false;
  TextEditingController illnessController = TextEditingController();
  TextEditingController complaintsController = TextEditingController();
  TextEditingController medicationController = TextEditingController();
  String complaintsControllerError = '';
  String medicationControllerError = '';
  String illnessControllerError = '';
  final formKey = GlobalKey<FormState>();

  getHistory(SOAPViewModel model) async {
    widget.changeLoadingState(true);
    GetHistoryReqModel getHistoryReqModel = GetHistoryReqModel(
        patientMRN: widget.patientInfo.patientMRN,
        episodeID: widget.patientInfo.episodeNo.toString(),
        appointmentNo: widget.patientInfo.appointmentNo,
        doctorID: '',
        editedBy: '');

    await model.getPatientHistories(getHistoryReqModel,isFirst: true);

    if (model.patientHistoryList.isNotEmpty) {
      if (model.historyFamilyList.isEmpty) {
        await model.getMasterLookup(MasterKeysService.HistoryFamily);
      }
      if (model.historyMedicalList.isEmpty) {
        await model.getMasterLookup(MasterKeysService.HistoryMedical);
      }
      if (model.historySurgicalList.length == 0) {
        await model.getMasterLookup(MasterKeysService.HistorySurgical);
      }
      if (model.historySportList.length == 0) {
        await model.getMasterLookup(MasterKeysService.HistorySports);
      }

      model.patientHistoryList.forEach((element) {
        if (element.historyType ==
            MasterKeysService.HistoryFamily.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistoryFamily,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory = MySelectedHistory(
                selectedHistory: history,
                isChecked: element.isChecked,
                remark: element.remarks);

            widget.myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType ==
            MasterKeysService.HistoryMedical.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistoryMedical,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory = MySelectedHistory(
                selectedHistory: history,
                isChecked: element.isChecked,
                remark: element.remarks);

            widget.myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType ==
            MasterKeysService.HistorySports.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistorySports,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory = MySelectedHistory(
                selectedHistory: history,
                isChecked: element.isChecked,
                remark: element.remarks);

            widget.myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType ==
            MasterKeysService.HistorySurgical.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistorySurgical,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory = MySelectedHistory(
                selectedHistory: history,
                isChecked: element.isChecked,
                remark: element.remarks);

            widget.myHistoryList.add(mySelectedHistory);
          }
        }
      });
    }
  }

  getAllergies(SOAPViewModel model) async {
    GeneralGetReqForSOAP generalGetReqForSOAP = GeneralGetReqForSOAP(
        patientMRN: widget.patientInfo.patientMRN,
        episodeId: widget.patientInfo.episodeNo,
        appointmentNo: widget.patientInfo.appointmentNo,
        doctorID: '',
        editedBy: '');
    await model.getPatientAllergy(generalGetReqForSOAP);
    if (model.patientAllergiesList.isNotEmpty) {
      if (model.allergiesList.isEmpty)
        await model.getMasterLookup(MasterKeysService.Allergies);
      if (model.allergySeverityList.isEmpty)
        await model.getMasterLookup(MasterKeysService.AllergySeverity);

      model.patientAllergiesList.forEach((element) {
        MasterKeyModel selectedAllergy = model.getOneMasterKey(
            masterKeys: MasterKeysService.Allergies,
            id: element.allergyDiseaseId,
            typeId: element.allergyDiseaseType);
        MasterKeyModel selectedAllergySeverity;
        if (element.severity == 0) {
          selectedAllergySeverity = MasterKeyModel(
              id: 0,
              typeId: MasterKeysService.AllergySeverity.getMasterKeyService(), nameAr: '', nameEn: '');
        } else {
           selectedAllergySeverity = model.getOneMasterKey(
            masterKeys: MasterKeysService.AllergySeverity,
            id: element.severity,
          );
        }

        MySelectedAllergy mySelectedAllergy = MySelectedAllergy(
            selectedAllergy: selectedAllergy,
            isChecked: element.isChecked,
            createdBy: element.createdBy,
            remark: element.remarks,
            selectedAllergySeverity: selectedAllergySeverity);
        if (selectedAllergy != null && selectedAllergySeverity != null)
          widget.myAllergiesList.add(mySelectedAllergy);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        widget.myAllergiesList.clear();
        widget.myHistoryList.clear();

        GetChiefComplaintReqModel getChiefComplaintReqModel =
            GetChiefComplaintReqModel(
                patientMRN: widget.patientInfo.patientMRN,
                appointmentNo: widget.patientInfo.appointmentNo,
                episodeId: widget.patientInfo.episodeNo,
                episodeID: widget.patientInfo.episodeNo,
                doctorID: '');
        await model.getPatientChiefComplaint(getChiefComplaintReqModel);
        if (model.patientChiefComplaintList.isNotEmpty) {
          isChiefExpand = true;
          complaintsController.text = Helpers.parseHtmlString(
              model.patientChiefComplaintList[0].chiefComplaint);
          illnessController.text = model.patientChiefComplaintList[0].hopi;
          medicationController.text =!(model.patientChiefComplaintList[0].currentMedication).isNotEmpty ? model.patientChiefComplaintList[0].currentMedication + '\n  \n':model.patientChiefComplaintList[0].currentMedication;
        }

        await getHistory(model);
        await getAllergies(model);

        widget.changeLoadingState(false);

      },
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: false,
        backgroundColor: Theme
            .of(context)
            .scaffoldBackgroundColor,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Center(
            child: FractionallySizedBox(
              widthFactor: 0.9,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [

                  SOAPStepHeader(currentIndex: widget.currentIndex, changePageViewIndex:widget.changePageViewIndex),
                  ExpandableSOAPWidget(
                    headerTitle: TranslationBase.of(context)
                        .chiefComplaints
                        ,
                    onTap: () {
                      setState(() {
                        isChiefExpand = !isChiefExpand;
                      });
                    },
                    child: UpdateChiefComplaints(
                      formKey: formKey,
                      complaintsController: complaintsController,
                      illnessController: illnessController,
                      medicationController: medicationController,
                      complaintsControllerError: complaintsControllerError,
                      illnessControllerError: illnessControllerError,
                      medicationControllerError: medicationControllerError,
                    ),
                    isExpanded: isChiefExpand,
                  ),
                  SizedBox(
                    height: 30,
                  ),


                  ExpandableSOAPWidget(
                    headerTitle: TranslationBase
                        .of(context)
                        .histories,
                    isRequired: false,
                    onTap: () {
                      setState(() {
                        isHistoryExpand = !isHistoryExpand;
                      });
                    },
                    child: Column(
                      children: [
                        UpdateHistoryWidget(myHistoryList: widget.myHistoryList)
                      ],
                    ),
                    isExpanded: isHistoryExpand,
                  ),
                  SizedBox(
                    height: 30,
                  ),


                  ExpandableSOAPWidget(
                    headerTitle: TranslationBase
                        .of(context)
                        .allergiesSoap
                    ,
                    isRequired: false,
                    onTap: () {
                      setState(() {
                        isAllergiesExpand = !isAllergiesExpand;
                      });
                    },
                    child: Column(
                      children: [
                        UpdateAllergiesWidget(myAllergiesList: widget
                            .myAllergiesList,),
                        SizedBox(
                          height: 30,
                        ),
                      ],
                    ),
                    isExpanded: isAllergiesExpand,
                  ),
                  SizedBox(
                    height:MediaQuery.of(context).size.height * 0.16,
                  ),
                ],
              ),
            ),
          ),
        ),
        bottomSheet: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(0.0),
            ),
            border: Border.all(
                color: HexColor('#707070'),
                width: 0),
          ),
          height: MediaQuery
            .of(context)
            .size
            .height * 0.1,
          width: double.infinity,

          child: Column(
            children: [
              SizedBox(
                height: 10,
              ),
              Container(child: FractionallySizedBox(
                widthFactor: .80,
                child: Center(
                  child: AppButton(
                    title: TranslationBase
                        .of(context)
                        .next,
                    fontWeight: FontWeight.w600,
                    color:Colors.red[700],
                    loading: model.state == ViewState.BusyLocal,
                    onPressed: () async {
                      addSubjectiveInfo(
                          model: model,
                          myAllergiesList: widget.myAllergiesList,
                          myHistoryList: widget.myHistoryList);
                    },
                  ),
                ),
              ),),
              SizedBox(
                height: 5,
              ),
            ],
          ),),
      ),
    );
  }

  addSubjectiveInfo({SOAPViewModel model,
    List<MySelectedAllergy> myAllergiesList,
    List<MySelectedHistory> myHistoryList}) async {
    formKey.currentState.save();
    formKey.currentState.validate();

    complaintsControllerError = '';
    medicationControllerError = '';
    illnessControllerError = '';
    if (complaintsController.text.isNotEmpty &&
        illnessController.text.isNotEmpty &&
        complaintsController.text.length > 25) {
      await postChiefComplaint(model: model);
      if (model.state == ViewState.ErrorLocal) {
        Helpers.showErrorToast(model.error);
      }

      if (myHistoryList.length != 0) {
        await postHistories(model: model, myHistoryList: myHistoryList);
        if (model.state == ViewState.ErrorLocal) {
          Helpers.showErrorToast(model.error);
        }
      }
      if (myAllergiesList.length != 0) {
        await postAllergy(myAllergiesList: myAllergiesList, model: model);
        if (model.state == ViewState.ErrorLocal) {
          Helpers.showErrorToast(model.error);
        }
      }
      widget.changeLoadingState(true);

      widget.changePageViewIndex(1);

    } else {
      setState(() {
        if (complaintsController.text.isEmpty) {
          complaintsControllerError = TranslationBase
              .of(context)
              .emptyMessage;
        } else if (complaintsController.text.length < 25) {
          complaintsControllerError = TranslationBase
              .of(context)
              .chiefComplaintLength;
        }

        if (illnessController.text.isEmpty) {
          illnessControllerError = TranslationBase
              .of(context)
              .emptyMessage;
        }

        if (medicationController.text.isEmpty) {
          medicationControllerError = TranslationBase
              .of(context)
              .emptyMessage;
        }
      });
      Helpers.showErrorToast(TranslationBase
          .of(context)
          .chiefComplaintErrorMsg);
    }


  }

  postAllergy(
      {List<MySelectedAllergy> myAllergiesList, SOAPViewModel model}) async {
    PostAllergyRequestModel postAllergyRequestModel =
        new PostAllergyRequestModel();

    Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

    DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
    widget.myAllergiesList.forEach((allergy) {
      if (postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM ==
          null)
        postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM = [];
      postAllergyRequestModel.listHisProgNotePatientAllergyDiseaseVM.add(
          ListHisProgNotePatientAllergyDiseaseVM(
              allergyDiseaseId: allergy.selectedAllergy.id,
              allergyDiseaseType: allergy.selectedAllergy.typeId,
              patientMRN: widget.patientInfo.patientMRN,
              episodeId: widget.patientInfo.episodeNo,
              appointmentNo: widget.patientInfo.appointmentNo,
              severity: allergy.selectedAllergySeverity.id,
              remarks: allergy.remark,
              createdBy: allergy.createdBy??doctorProfile.doctorID,
              createdOn: DateTime.now().toIso8601String(),
              editedBy: doctorProfile.doctorID,
              editedOn: DateTime.now().toIso8601String(),
              isChecked: allergy.isChecked,
              isUpdatedByNurse: false));
    });
    if (model.patientAllergiesList.isEmpty) {
      await model.postAllergy(postAllergyRequestModel);
    } else {
      await model.patchAllergy(postAllergyRequestModel);
    }

    GeneralGetReqForSOAP generalGetReqForSOAP = GeneralGetReqForSOAP(
        patientMRN: widget.patientInfo.patientMRN,
        episodeId: widget.patientInfo.episodeNo,
        appointmentNo: widget.patientInfo.appointmentNo,
        doctorID: '',
        editedBy: '');
    await model.getPatientAllergy(generalGetReqForSOAP, isLocalBusy : true);

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

  postHistories(
      {List<MySelectedHistory> myHistoryList, SOAPViewModel model}) async {
    PostHistoriesRequestModel postHistoriesRequestModel =
    new PostHistoriesRequestModel(doctorID: '');
    widget.myHistoryList.forEach((history) {
      if (postHistoriesRequestModel.listMedicalHistoryVM == null)
        postHistoriesRequestModel.listMedicalHistoryVM = [];
      postHistoriesRequestModel.listMedicalHistoryVM.add(ListMedicalHistoryVM(
        patientMRN: widget.patientInfo.patientMRN,
        episodeId: widget.patientInfo.episodeNo,
        appointmentNo: widget.patientInfo.appointmentNo,
        remarks: "",
        historyId: history.selectedHistory.id,
        historyType: history.selectedHistory.typeId,
        isChecked: history.isChecked,
      ));
    });


    if (model.patientHistoryList.isEmpty) {
      await model.postHistories(postHistoriesRequestModel);
    } else {
      await model.patchHistories(postHistoriesRequestModel);
    }


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

  postChiefComplaint({SOAPViewModel model}) async {
    formKey.currentState.save();
    if(formKey.currentState.validate()){
      PostChiefComplaintRequestModel postChiefComplaintRequestModel =
          new PostChiefComplaintRequestModel(
              patientMRN: widget.patientInfo.patientMRN,
              episodeID: widget.patientInfo.episodeNo,
              appointmentNo: widget.patientInfo.appointmentNo,
              chiefComplaint: complaintsController.text,
              currentMedication: medicationController.text,
              hopi: illnessController.text,
              isLactation: false,
              ispregnant: false,
              doctorID: '',

              numberOfWeeks: 0);
      if (model.patientChiefComplaintList.isEmpty) {
        postChiefComplaintRequestModel.editedBy = '';
        await model.postChiefComplaint(postChiefComplaintRequestModel);
      } else {
        await model.patchChiefComplaint(postChiefComplaintRequestModel);
      }
    }
  }
}





