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/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_allergy.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_history.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/SOAP_step_header.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/expandable_SOAP_widget.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/screens/patients/profile/soap_update_vida_plus/subjective/medication/update_medication_widget.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/subjective/present_illness/update_present_illness.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';

import '../../../../../core/model/SOAP/allergy/get_patient_allergies_list_vida_plus.dart';
import 'allergies/update_allergies_widget.dart';
import 'chief_complaint/chief_complaints.dart';


class UpdateSubjectivePageVidaPlus extends StatefulWidget {
  final Function changePageViewIndex;
  final Function changeLoadingState;
  final PatiantInformtion patientInfo;
  final int currentIndex;

  UpdateSubjectivePageVidaPlus(
      {Key? key, required this.changePageViewIndex, required this.patientInfo, required this.changeLoadingState, required this.currentIndex});

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

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

  final formKey = GlobalKey<FormState>();
  List<PatientAllergiesVidaPlus> myAllergiesList = [];
  List<MySelectedHistory> myHistoryList = [];

  // 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 {
    await model.getAllergiesVidaPlus(widget.patientInfo);
    myAllergiesList = model.patientAllergiesVidaPlus;
    // 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 {
        WidgetsBinding.instance.addPostFrameCallback((_) async {
          myAllergiesList.clear();
          myHistoryList.clear();
          model.setSubjectiveCallBack(this);
          // await model.onUpdateSubjectStepStart(widget.patientInfo);

          if (model.patientChiefComplaintList.isNotEmpty) {
            isChiefExpand = true;
            complaintsController.text = Utils.parseHtmlString(
                model.patientChiefComplaintList[0].chiefComplaint!);
            illnessController.text = model.patientChiefComplaintList[0].hopi!;
            medicationController.text =
            model.patientChiefComplaintList[0].currentMedication != null
                ? !(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(
                          complaints: [],
                          patientInfo: widget.patientInfo,
                        ),
                        isExpanded: isChiefExpand,
                      ),
                      SizedBox(
                        height: SizeConfig.heightMultiplier! *
                            (SizeConfig.isHeightVeryShort ? 4 : 2),
                      ),
                      if (widget.patientInfo.admissionNo == null)
                        ExpandableSOAPWidget(
                          headerTitle: TranslationBase
                              .of(context)
                              .historyOfIllness,
                          isRequired: false,
                          onTap: () {
                            setState(() {
                              isHistoryExpand = !isHistoryExpand;
                            });
                          },
                          child: Column(
                            children: [UpdatePresentIllness(widget.patientInfo)],
                          ),
                          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: [
                              UpdateAllergiesWidgetVidaPlus(
                                myAllergiesList: myAllergiesList,
                                  patientInfo: widget.patientInfo
                              ),
                              SizedBox(
                                height: 30,
                              ),
                            ],
                          ),
                          isExpanded: isAllergiesExpand,
                        ),
                      SizedBox(
                        height: SizeConfig.heightMultiplier! *
                            (SizeConfig.isHeightVeryShort ? 4 : 2),
                      ),
                      ExpandableSOAPWidget(
                        headerTitle: TranslationBase
                            .of(context)
                            .currentMedications,
                        onTap: () {
                          setState(() {
                            isMedicationExpand = !isMedicationExpand;
                          });
                        },
                        child:  Column(children: [
                          SizedBox(
                            height: SizeConfig.heightMultiplier! *
                                (SizeConfig.isHeightVeryShort ? 4 : 2),
                          ),
                        UpdateMedicationWidget(
                          patientInfo:  widget.patientInfo,
                        ),
                        SizedBox(
                          height: 10,
                        ),

                      ],),
                        isExpanded: isMedicationExpand,
                      ),
                      SizedBox(
                        height: SizeConfig.heightMultiplier! *
                            (SizeConfig.isHeightVeryShort ? 20 : 10),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
    );
  }

  addSubjectiveInfo({required SOAPViewModel model, required List<
      MySelectedAllergy> myAllergiesList, required 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) {
      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;
        }

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

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

      widget.changeLoadingState(false);
      Utils.showErrorToast(TranslationBase
          .of(context)
          .chiefComplaintErrorMsg);
    }
  }


  Function nextFunction(model) {
  //need to be implemented ..
  return (){};
  }

}

//
// UpdateMedicationWidget(
// medicationController: medicationController,
// ),
// SizedBox(
// height: 10,
// ),
// AppTextFieldCustom(
// hintText: TranslationBase.of(context).currentMedications,
// controller: medicationController,
// maxLines: 25,
// minLines: 7,
// hasBorder: true,
// inputType: TextInputType.multiline,
// // validationError: medicationControllerError != '' ? medicationControllerError : "",
// onClick: () {},
// onChanged: (value) {},
// onFieldSubmitted: () {},
// ),
// SizedBox(
// height: 10,
// )