import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/config/size_config.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/selected_items/my_selected_allergy.dart';
import 'package:doctor_app_flutter/models/SOAP/selected_items/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/screens/patients/profile/soap_update/soap_utils.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/subjective/subjective_call_back.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 PatiantInformtion patientInfo;
  final int currentIndex;

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

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

class _UpdateSubjectivePageState extends State<UpdateSubjectivePage> implements SubjectiveCallBack {
  bool isChiefExpand = false;
  bool isHistoryExpand = false;
  bool isAllergiesExpand = false;
  TextEditingController illnessController = TextEditingController();
  TextEditingController complaintsController = TextEditingController();
  TextEditingController medicationController = TextEditingController();

  final formKey = GlobalKey<FormState>();
  List<MySelectedAllergy> myAllergiesList = List();
  List<MySelectedHistory> myHistoryList = List();

  getHistory(SOAPViewModel model) async {
    widget.changeLoadingState(true);

    model.complaintsControllerError = '';
    model.medicationControllerError = '';
    model.illnessControllerError = '';
    GetHistoryReqModel getHistoryReqModel = GetHistoryReqModel(
        patientMRN: widget.patientInfo.patientMRN,
        episodeID: widget.patientInfo.episodeNo.toString(),
        appointmentNo: int.parse(widget.patientInfo.appointmentNo.toString()),
        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 =
                SoapUtils.generateMySelectedHistory(
                history: history, isChecked: element.isChecked, remark: element.remarks, isLocal: false);
            myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType == MasterKeysService.HistoryMedical.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistoryMedical,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory =
                SoapUtils.generateMySelectedHistory(
                history: history, isChecked: element.isChecked, remark: element.remarks, isLocal: false);
            myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType == MasterKeysService.HistorySports.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistorySports,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory =
                SoapUtils.generateMySelectedHistory(
                history: history, isChecked: element.isChecked, remark: element.remarks, isLocal: false);
            myHistoryList.add(mySelectedHistory);
          }
        }
        if (element.historyType == MasterKeysService.HistorySurgical.getMasterKeyService()) {
          MasterKeyModel history = model.getOneMasterKey(
            masterKeys: MasterKeysService.HistorySurgical,
            id: element.historyId,
          );
          if (history != null) {
            MySelectedHistory mySelectedHistory =
                SoapUtils.generateMySelectedHistory(
                history: history, isChecked: element.isChecked, remark: element.remarks, isLocal: false);
            myHistoryList.add(mySelectedHistory);
          }
        }
      });
    }
  }

  getAllergies(SOAPViewModel model) async {
    GeneralGetReqForSOAP generalGetReqForSOAP = GeneralGetReqForSOAP(
        patientMRN: widget.patientInfo.patientMRN,
        episodeId: widget.patientInfo.episodeNo,
        appointmentNo: int.parse(widget.patientInfo.appointmentNo.toString()),
        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 = SoapUtils.generateMySelectedAllergy(
            allergy: selectedAllergy,
            isChecked: element.isChecked,
            createdBy: element.createdBy,
            remark: element.remarks,
            isLocal: false,
            allergySeverity: selectedAllergySeverity);

        if (selectedAllergy != null && selectedAllergySeverity != null) myAllergiesList.add(mySelectedAllergy);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        myAllergiesList.clear();
        myHistoryList.clear();
        model.setSubjectiveCallBack(this);
        GetChiefComplaintReqModel getChiefComplaintReqModel = GetChiefComplaintReqModel(
            admissionNo: widget.patientInfo.admissionNo != null ? int.parse(widget.patientInfo.admissionNo) : null,
            patientMRN: widget.patientInfo.patientMRN,
            appointmentNo: widget.patientInfo.appointmentNo != null
                ? int.parse(widget.patientInfo.appointmentNo.toString())
                : null,
            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;
        }
        if (widget.patientInfo.admissionNo == null) {
          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,
                    patientInfo: widget.patientInfo,
                  ),
                  ExpandableSOAPWidget(
                    headerTitle: TranslationBase.of(context).chiefComplaints,
                    onTap: () {
                      setState(() {
                        isChiefExpand = !isChiefExpand;
                      });
                    },
                    child: UpdateChiefComplaints(
                      formKey: formKey,
                      complaintsController: complaintsController,
                      illnessController: illnessController,
                      medicationController: medicationController,
                      complaintsControllerError:
                          model.complaintsControllerError,
                      illnessControllerError: model.illnessControllerError,
                      medicationControllerError:
                          model.medicationControllerError,
                    ),
                    isExpanded: isChiefExpand,
                  ),
                  SizedBox(
                    height: SizeConfig.heightMultiplier * (SizeConfig.isHeightVeryShort ? 4 : 2),
                  ),
                  if (widget.patientInfo.admissionNo == null)
                    ExpandableSOAPWidget(
                      headerTitle: TranslationBase.of(context).histories,
                      isRequired: false,
                      onTap: () {
                        setState(() {
                          isHistoryExpand = !isHistoryExpand;
                        });
                      },
                      child: Column(
                        children: [UpdateHistoryWidget(myHistoryList: myHistoryList)],
                      ),
                      isExpanded: isHistoryExpand,
                    ),
                  SizedBox(
                    height: SizeConfig.heightMultiplier * (SizeConfig.isHeightVeryShort ? 4 : 2),
                  ),
                  if (widget.patientInfo.admissionNo == null)
                    ExpandableSOAPWidget(
                      headerTitle: TranslationBase.of(context).allergiesSoap,
                      isRequired: false,
                      onTap: () {
                        setState(() {
                          isAllergiesExpand = !isAllergiesExpand;
                        });
                      },
                      child: Column(
                        children: [
                          UpdateAllergiesWidget(
                            myAllergiesList: myAllergiesList,
                          ),
                          SizedBox(
                            height: 30,
                          ),
                        ],
                      ),
                      isExpanded: isAllergiesExpand,
                    ),
                  SizedBox(
                    height: SizeConfig.heightMultiplier * (SizeConfig.isHeightVeryShort ? 20 : 10),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  addSubjectiveInfo(
      {SOAPViewModel model, List<MySelectedAllergy> myAllergiesList, List<MySelectedHistory> myHistoryList}) async {
    if (FocusScope.of(context).hasFocus) FocusScope.of(context).unfocus();
    widget.changeLoadingState(true);
    formKey.currentState.save();
    formKey.currentState.validate();

    model.complaintsControllerError = '';
    model.medicationControllerError = '';
    model.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) {
          model.complaintsControllerError =
              TranslationBase.of(context).emptyMessage;
        } else if (complaintsController.text.length < 25) {
          model.complaintsControllerError =
              TranslationBase.of(context).chiefComplaintLength;
        }

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

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

      widget.changeLoadingState(false);
      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);
    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);
    }

    if (model.state == ViewState.ErrorLocal) {
      Helpers.showErrorToast(model.error);
    }
    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: '');
    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(
          admissionNo: widget.patientInfo.admissionNo != null ? int.parse(widget.patientInfo.admissionNo) : null,
          patientMRN: widget.patientInfo.patientMRN,
          episodeID: widget.patientInfo.episodeNo ?? 0,
          appointmentNo: widget.patientInfo.appointmentNo ?? 0,
          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 {
        postChiefComplaintRequestModel.editedBy = '';
        await model.patchChiefComplaint(postChiefComplaintRequestModel);
      }
    }
  }

  @override
  Function nextFunction(model) {
    addSubjectiveInfo(model: model, myAllergiesList: myAllergiesList, myHistoryList: myHistoryList);
  }
}
