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/GetPhysicalExamReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/my_selected_examination.dart';
import 'package:doctor_app_flutter/models/SOAP/post_physical_exam_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/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../shared_soap_widgets/SOAP_open_items.dart';
import '../shared_soap_widgets/SOAP_step_header.dart';
import '../shared_soap_widgets/expandable_SOAP_widget.dart';
import 'add_examination_page.dart';
import 'examination_item_card.dart';

class UpdateObjectivePage extends StatefulWidget {
  final Function changePageViewIndex;
  final Function changeLoadingState;
  final int currentIndex;
  final List<MySelectedExamination> mySelectedExamination;
  final PatiantInformtion patientInfo;

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

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

class _UpdateObjectivePageState extends State<UpdateObjectivePage> {
  bool isSysExaminationExpand = false;

  BoxDecoration containerBorderDecoration(
      Color containerColor, Color borderColor) {
    return BoxDecoration(
      color: containerColor,
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(6)),
      border: Border.fromBorderSide(BorderSide(
        color: borderColor,
        width: 0.5,
      )),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model) async {
          widget.mySelectedExamination.clear();
          GetPhysicalExamReqModel getPhysicalExamReqModel =
              GetPhysicalExamReqModel(
                  patientMRN: widget.patientInfo.patientMRN,
                  episodeID: widget.patientInfo.episodeNo.toString(),
                  appointmentNo: widget.patientInfo.appointmentNo);

          await model.getPatientPhysicalExam(getPhysicalExamReqModel);
          if (model.patientPhysicalExamList.isNotEmpty) {
            if (model.physicalExaminationList.length == 0) {
              await model
                  .getMasterLookup(MasterKeysService.PhysicalExamination);
            }
            model.patientPhysicalExamList.forEach((element) {
              MasterKeyModel examMaster = model.getOneMasterKey(
                masterKeys: MasterKeysService.PhysicalExamination,
                id: element.examId,
              );
              MySelectedExamination tempEam = MySelectedExamination(
                  selectedExamination: examMaster,
                  remark: element.remarks,
                  isNormal: element.isNormal,
                  createdBy: element.createdBy,
                  notExamined: element.notExamined,
                  isNew: element.isNew,
                  isAbnormal: element.isAbnormal);
              widget.mySelectedExamination.add(tempEam);
            });
          }

          widget.changeLoadingState(false);
        },
        builder: (_, model, w) => AppScaffold(
          isShowAppBar: false,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        body: SingleChildScrollView(
          child: Center(
            child: FractionallySizedBox(
              widthFactor: 0.9,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SOAPStepHeader(
                      currentIndex: widget.currentIndex,
                      changePageViewIndex: widget.changePageViewIndex),
                  ExpandableSOAPWidget(
                    headerTitle:
                        TranslationBase.of(context).physicalSystemExamination,
                    onTap: () {
                      setState(() {
                        isSysExaminationExpand = !isSysExaminationExpand;
                      });
                    },
                    child: Column(
                      children: [
                        SOAPOpenItems(label: "${TranslationBase.of(context).addExamination}",onTap: () {
                          openExaminationList(context);
                        },),
                        Column(
                          children:
                              widget.mySelectedExamination.map((examination) {
                                return ExaminationItemCard(examination, () {
                              removeExamination(
                                  examination.selectedExamination);
                            });
                          }).toList(),
                        )
                      ],

                    ),
                    isExpanded: isSysExaminationExpand,
                  ),
                  SizedBox(height: MediaQuery
                      .of(context)
                      .size
                      .height * 0.12,)
                ],
              ),
            ),
          ),
        ),
          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: FractionallySizedBox(
              widthFactor: 0.9,
              child: Row(
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width *0.4,
                    child: AppButton(
                      title: TranslationBase.of(context).previous,
                      color: Colors.grey[300],
                      fontColor: Colors.black,
                      fontWeight: FontWeight.w600,
                      onPressed: () {
                        widget.changePageViewIndex(0);
                      },
                    ),
                  ),
                  SizedBox(
                   width: MediaQuery.of(context).size.width *0.1,
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width *0.4,
                    child: AppButton(
                      title: TranslationBase.of(context).next,
                      fontWeight: FontWeight.w600,
                      loading: model.state == ViewState.BusyLocal,
                      color: widget.mySelectedExamination != null &&
                          widget.mySelectedExamination.length > 0
                          ?  Colors.red[700]
                          : HexColor("#A5A5A5"),
                      fontColor: widget.mySelectedExamination != null &&
                          widget.mySelectedExamination.length > 0 ? Colors.white : HexColor("#5A5A5A"),
                      disabled: widget.mySelectedExamination != null &&
                          widget.mySelectedExamination.length > 0
                          ? false
                          : true,
                      onPressed: () async {
                        await submitUpdateObjectivePage(model);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
      ),
    );
  }

  submitUpdateObjectivePage(SOAPViewModel model) async {
    if (widget.mySelectedExamination.isNotEmpty) {
      Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

      DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
      PostPhysicalExamRequestModel postPhysicalExamRequestModel =
          new PostPhysicalExamRequestModel();
      widget.mySelectedExamination.forEach((exam) {
        if (postPhysicalExamRequestModel.listHisProgNotePhysicalExaminationVM ==
            null)
          postPhysicalExamRequestModel.listHisProgNotePhysicalExaminationVM =
              [];

        postPhysicalExamRequestModel.listHisProgNotePhysicalExaminationVM
            .add(ListHisProgNotePhysicalExaminationVM(
                patientMRN: widget.patientInfo.patientMRN,
                episodeId: widget.patientInfo.episodeNo,
                appointmentNo: widget.patientInfo.appointmentNo,
                remarks: exam.remark ?? '',
                createdBy: exam.createdBy ?? doctorProfile.doctorID,
                createdOn: DateTime.now().toIso8601String(),
                editedBy: doctorProfile.doctorID,
                editedOn: DateTime.now().toIso8601String(),
                examId: exam.selectedExamination.id,
                examType: exam.selectedExamination.typeId,
                isAbnormal: exam.isAbnormal,
                isNormal: exam.isNormal,
                notExamined: exam.notExamined,
                examinationType: exam.isNormal
                    ? 1
                    : exam.isAbnormal
                        ? 2
                        : 3,
                examinationTypeName: exam.isNormal
                    ? "Normal"
                    : exam.isAbnormal
                        ? 'AbNormal'
                        : "Not Examined",
                isNew: exam.isNew));
      });

      if (model.patientPhysicalExamList.isEmpty) {
        await model.postPhysicalExam(postPhysicalExamRequestModel);
      } else {
        await model.patchPhysicalExam(postPhysicalExamRequestModel);
      }

      if (model.state == ViewState.ErrorLocal) {
        Helpers.showErrorToast(model.error);
      } else {
        widget.changeLoadingState(true);

        widget.changePageViewIndex(2);
      }
    } else {
      Helpers.showErrorToast(TranslationBase.of(context).examinationErrorMsg);
    }
  }

  removeExamination(MasterKeyModel masterKey) {
    Iterable<MySelectedExamination> history = widget.mySelectedExamination
        .where((element) =>
            masterKey.id == element.selectedExamination.id &&
            masterKey.typeId == element.selectedExamination.typeId);

    if (history.length > 0)
      setState(() {
        widget.mySelectedExamination.remove(history.first);
      });
  }

  openExaminationList(BuildContext context) {
    Navigator.push(
      context,
      FadePage(
        page: AddExaminationPage(
            mySelectedExamination: widget.mySelectedExamination,
            addSelectedExamination: () {
              setState(() {
                Navigator.of(context).pop();
              });
            },
            removeExamination: (masterKey) => removeExamination(masterKey)),
      ),
    );
    /*showModalBottomSheet(
        backgroundColor: Colors.white,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return AddExaminationDailog(
            mySelectedExamination: widget.mySelectedExamination,
            addSelectedExamination: () {
              setState(() {
                Navigator.of(context).pop();
              });
            },
            removeExamination: (masterKey) => removeExamination(masterKey),
          );
        });*/
  }
}

class AddExaminationDailog extends StatefulWidget {
  final List<MySelectedExamination> mySelectedExamination;
  final Function addSelectedExamination;
  final Function(MasterKeyModel) removeExamination;

  const AddExaminationDailog(
      {Key key,
      this.mySelectedExamination,
      this.addSelectedExamination,
      this.removeExamination})
      : super(key: key);

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

class _AddExaminationDailogState extends State<AddExaminationDailog> {
  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
      heightFactor: 0.7,
      child: BaseView<SOAPViewModel>(
          onModelReady: (model) async {
            if (model.physicalExaminationList.length == 0) {
              await model
                  .getMasterLookup(MasterKeysService.PhysicalExamination);
            }
          },
          builder: (_, model, w) => AppScaffold(
                baseViewModel: model,
                isShowAppBar: false,
                body: Center(
                    child: Container(
                        child: FractionallySizedBox(
                  widthFactor: 0.9,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 16,
                        ),
                        AppText(
                          TranslationBase.of(context).physicalSystemExamination,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                        SizedBox(
                          height: 16,
                        ),
                      ]),
                ))),
              )),
    );
  }
}
