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/view_state.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/GetGetProgressNoteResModel.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/get_progress_note_req_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/progress_note/post_progress_note_request_model.dart';
import 'package:doctor_app_flutter/core/model/doctor/doctor_profile_model.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/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/plan/plan_call_back.dart';
import 'package:doctor_app_flutter/utils/date-utils.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/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';

import '../shared_soap_widgets/SOAP_step_header.dart';
import '../shared_soap_widgets/expandable_SOAP_widget.dart';

class UpdatePlanPage extends StatefulWidget {
  final Function changePageViewIndex;
  final PatiantInformtion patientInfo;
  final Function changeLoadingState;
  final Function changeStateFun;
  final SOAPViewModel sOAPViewModel;

  final int currentIndex;

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

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

class _UpdatePlanPageState extends State<UpdatePlanPage> implements PlanCallBack {
  bool isAddProgress = true;
  bool isProgressExpanded = true;
  GetPatientProgressNoteResModel patientProgressNote = GetPatientProgressNoteResModel();

  TextEditingController progressNoteController = TextEditingController(text: null);

  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
  void initState() {
    super.initState();
    if (patientProgressNote.planNote != null) {
      setState(() {
        isAddProgress = false;
      });
    }
  }

  getPatientProgressNote(SOAPViewModel model, {bool isAddProgress = false}) async {
    GetProgressNoteReqModel getGetProgressNoteReqModel = GetProgressNoteReqModel(
        appointmentNo: int.parse(widget.patientInfo.appointmentNo.toString()),
        patientMRN: widget.patientInfo.patientMRN,
        episodeID: widget.patientInfo.episodeNo.toString(),
        editedBy: '',
        doctorID: '');
    await widget.sOAPViewModel.getPatientProgressNote(getGetProgressNoteReqModel);

    ///TODO set progressNote in  model;
    if (widget.sOAPViewModel.patientProgressNoteList.isNotEmpty) {
      progressNoteController.text = Utils.parseHtmlString(widget.sOAPViewModel.patientProgressNoteList[0].planNote!);
      patientProgressNote.planNote = progressNoteController.text;

      patientProgressNote.createdByName = widget.sOAPViewModel.patientProgressNoteList[0].createdByName;
      patientProgressNote.createdOn = widget.sOAPViewModel.patientProgressNoteList[0].createdOn;
      patientProgressNote.editedOn = widget.sOAPViewModel.patientProgressNoteList[0].editedOn;
      patientProgressNote.editedByName = widget.sOAPViewModel.patientProgressNoteList[0].editedByName;
      patientProgressNote.appointmentNo = widget.sOAPViewModel.patientProgressNoteList[0].appointmentNo;
      setState(() {
        isAddProgress = isAddProgress;
        widget.sOAPViewModel.isAddProgress = isAddProgress;
        widget.sOAPViewModel.progressNoteText = progressNoteController.text;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model) async {
          widget.sOAPViewModel.setPlanCallBack(this);
          GetProgressNoteReqModel getGetProgressNoteReqModel = GetProgressNoteReqModel(
              appointmentNo: int.parse(widget.patientInfo.appointmentNo.toString()),
              patientMRN: widget.patientInfo.patientMRN,
              episodeID: widget.patientInfo.episodeNo.toString(),
              editedBy: '',
              doctorID: '');
          await widget.sOAPViewModel.getPatientProgressNote(getGetProgressNoteReqModel);

          if (widget.sOAPViewModel.patientProgressNoteList.isNotEmpty) {
            progressNoteController.text = Utils.parseHtmlString(widget.sOAPViewModel.patientProgressNoteList[0].planNote!);
            patientProgressNote.planNote = progressNoteController.text;
            patientProgressNote.createdByName = widget.sOAPViewModel.patientProgressNoteList[0].createdByName;
            patientProgressNote.createdOn = widget.sOAPViewModel.patientProgressNoteList[0].createdOn;
            patientProgressNote.editedOn = widget.sOAPViewModel.patientProgressNoteList[0].editedOn;
            patientProgressNote.editedByName = widget.sOAPViewModel.patientProgressNoteList[0].editedByName;
            patientProgressNote.appointmentNo = widget.sOAPViewModel.patientProgressNoteList[0].appointmentNo;
            widget.sOAPViewModel.progressNoteText = progressNoteController.text;

            setState(() {
              isAddProgress = false;
              widget.sOAPViewModel.isAddProgress = false;
            });
          }
          widget.changeLoadingState(false);
        },
        builder: (_, model, w) => AppScaffold(
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,
              isShowAppBar: false,
              body: SingleChildScrollView(
                physics: ScrollPhysics(),
                child: Center(
                  child: FractionallySizedBox(
                    widthFactor: 0.90,
                    child: Column(
                      children: [
                        SOAPStepHeader(
                          currentIndex: widget.currentIndex,
                          changePageViewIndex: widget.changePageViewIndex,
                          patientInfo: widget.patientInfo,
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        ExpandableSOAPWidget(
                          headerTitle: TranslationBase.of(context).progressNote,
                          onTap: () {
                            setState(() {
                              isProgressExpanded = !isProgressExpanded;
                            });
                          },
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  if (isAddProgress)
                                    Container(
                                      margin: EdgeInsets.only(left: 10, right: 10, top: 15),
                                      child: AppTextFieldCustom(
                                        hintText: TranslationBase.of(context).progressNote,
                                        controller: progressNoteController,
                                        minLines: 2,
                                        maxLines: 4,
                                        inputType: TextInputType.multiline,
                                        onChanged: (value) {
                                          setState(() {
                                            patientProgressNote.planNote = value;
                                            model.progressNoteText = value!;
                                            widget.changeStateFun();
                                          });
                                        },
                                        onFieldSubmitted: () {},
                                      ),
                                    ),
                                  SizedBox(
                                    height: 9,
                                  ),
                                  if (patientProgressNote.planNote != null && !isAddProgress)
                                    Container(
                                      margin: EdgeInsets.only(
                                        left: 5,
                                        right: 5,
                                      ),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  AppText(
                                                    'Appointment No: ',
                                                    fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3,
                                                    letterSpacing: -0.4,
                                                    color: Color(0xFF575757),
                                                  ),
                                                  AppText(
                                                    patientProgressNote.appointmentNo != null ? patientProgressNote.appointmentNo.toString() : '',
                                                    fontWeight: FontWeight.w600,
                                                    letterSpacing: -0.48,
                                                    color: Color(0xFF2B353E),
                                                    fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                  ),
                                                ],
                                              ),
                                              AppText(
                                                patientProgressNote.createdOn != null
                                                    ? AppDateUtils.getDayMonthYearDateFormatted(DateTime.parse(patientProgressNote.createdOn!))
                                                    : AppDateUtils.getDayMonthYearDateFormatted(DateTime.now()),
                                                fontWeight: FontWeight.w600,
                                                fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                              )
                                            ],
                                          ),
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.end,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              // Row(
                                              //   children: [
                                              //     AppText(
                                              //       'Condition: ',
                                              //       fontSize: 12,
                                              //     ),
                                              //     AppText(
                                              //         patientProgressNote.mName ??
                                              //             '',
                                              //         fontWeight: FontWeight.w600),
                                              //   ],
                                              // ),
                                              AppText(
                                                patientProgressNote.createdOn != null ? AppDateUtils.getHour(DateTime.parse(patientProgressNote.createdOn!)) : AppDateUtils.getHour(DateTime.now()),
                                                fontWeight: FontWeight.w600,
                                                color: Color(0xFF575757),
                                                fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                              )
                                            ],
                                          ),
                                          SizedBox(
                                            height: 8,
                                          ),
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            children: [
                                              Expanded(
                                                child: AppText(
                                                  progressNoteController.text,
                                                  fontSize: 10,
                                                ),
                                              ),
                                              InkWell(
                                                  onTap: () {
                                                    setState(() {
                                                      isAddProgress = true;
                                                      widget.sOAPViewModel.isAddProgress = true;
                                                    });
                                                  },
                                                  child: Icon(
                                                    DoctorApp.edit,
                                                    size: 18,
                                                  ))
                                            ],
                                          ),
                                        ],
                                      ),
                                    )
                                ],
                              ),
                            ],
                          ),
                          isExpanded: isProgressExpanded,
                        ),
                        SizedBox(
                          height: SizeConfig.heightMultiplier! * (SizeConfig.isHeightVeryShort ? 20 : 10),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ));
  }

  submitPlan(SOAPViewModel model) async {
    if (progressNoteController.text.isNotEmpty) {
      widget.changeLoadingState(true);
      PostProgressNoteRequestModel postProgressNoteRequestModel = new PostProgressNoteRequestModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeId: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          planNote: patientProgressNote.planNote,
          doctorID: widget.patientInfo.doctorId,
          createdBy: widget.patientInfo.doctorId,
          createdByName: widget.patientInfo.doctorName,
          editedBy: '');

      if (widget.sOAPViewModel.patientProgressNoteList.isEmpty) {
        await widget.sOAPViewModel.postProgressNote(postProgressNoteRequestModel);
      } else {
        Map<String, dynamic> profile = await sharedPref.getObj(DOCTOR_PROFILE);
        DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
        postProgressNoteRequestModel.editedBy = doctorProfile.doctorID;
        await widget.sOAPViewModel.patchProgressNote(postProgressNoteRequestModel);
      }

      if (widget.sOAPViewModel.state == ViewState.ErrorLocal) {
        Utils.showErrorToast(widget.sOAPViewModel.error);
      } else {
        GetProgressNoteReqModel getGetProgressNoteReqModel = GetProgressNoteReqModel(
            appointmentNo: int.parse(widget.patientInfo.appointmentNo.toString()),
            patientMRN: widget.patientInfo.patientMRN,
            episodeID: widget.patientInfo.episodeNo.toString(),
            editedBy: '',
            doctorID: '');
        await widget.sOAPViewModel.getPatientProgressNote(getGetProgressNoteReqModel);
        if (widget.sOAPViewModel.patientProgressNoteList.isNotEmpty) {
          progressNoteController.text = Utils.parseHtmlString(widget.sOAPViewModel.patientProgressNoteList[0].planNote!);
          patientProgressNote.planNote = progressNoteController.text;
          patientProgressNote.createdByName = widget.sOAPViewModel.patientProgressNoteList[0].createdByName;
          patientProgressNote.createdOn = widget.sOAPViewModel.patientProgressNoteList[0].createdOn;
          patientProgressNote.editedOn = widget.sOAPViewModel.patientProgressNoteList[0].editedOn;
          patientProgressNote.editedByName = widget.sOAPViewModel.patientProgressNoteList[0].editedByName;
          patientProgressNote.appointmentNo = widget.sOAPViewModel.patientProgressNoteList[0].appointmentNo;

          setState(() {
            isAddProgress = false;
            widget.sOAPViewModel.isAddProgress = false;
          });
        }

        Navigator.of(context).pop();
        Utils.showErrorToast("Episode Created Successfully");
      }
      widget.changeLoadingState(false);
    } else {
      Utils.showErrorToast(TranslationBase.of(context).progressNoteErrorMsg);
    }
  }

  @override
  nextFunction(model) {
    if (progressNoteController.text.isNotEmpty) {
      if (isAddProgress) {
        submitPlan(model);
      } else {
        Navigator.of(context).pop();
      }
    } else {
      Utils.showErrorToast(TranslationBase.of(context).progressNoteErrorMsg);
    }
  }
}
