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/viewModel/SOAP_view_model.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/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:flutter/material.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);
    if (model.patientHistoryList.isNotEmpty) {
      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 {
    if (model.patientAllergiesList.isNotEmpty) {
      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);
        await model.onUpdateSubjectStepStart(widget.patientInfo);

        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 model.postSubjectServices(
        patientInfo: widget.patientInfo,
        complaintsText: complaintsController.text,
        medicationText: medicationController.text,
        illnessText: illnessController.text,
        myHistoryList: myHistoryList,
        myAllergiesList: myAllergiesList,
      );

      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);
    }
  }

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