import 'package:doctor_app_flutter/config/shared_pref_kay.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/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/models/SOAP/GetGetProgressNoteReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/GetGetProgressNoteResModel.dart';
import 'package:doctor_app_flutter/models/SOAP/post_progress_note_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/date-utils.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/shared/text_fields/app-textfield-custom.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';

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

  final int currentIndex;
  GetPatientProgressNoteResModel patientProgressNote;

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

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

class _UpdatePlanPageState extends State<UpdatePlanPage> {
  bool isAddProgress = true;
  bool isProgressExpanded = true;

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


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

        if (model.patientProgressNoteList.isNotEmpty) {
          progressNoteController.text = Helpers
              .parseHtmlString(model.patientProgressNoteList[0].planNote);
           widget.patientProgressNote.planNote = progressNoteController.text;
           widget.patientProgressNote.createdByName = model.patientProgressNoteList[0].createdByName;
           widget.patientProgressNote.createdOn = model.patientProgressNoteList[0].createdOn;
           widget.patientProgressNote.editedOn = model.patientProgressNoteList[0].editedOn;
           widget.patientProgressNote.editedByName = model.patientProgressNoteList[0].editedByName;
          setState(() {
            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),

                  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){
                                    widget.patientProgressNote.planNote = value;
                                  },
                                ),
                              ),
                            SizedBox(
                              height: 9,
                            ),
                            if ( widget.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: 12,),
                                            AppText(widget.patientProgressNote.appointmentNo??'',fontWeight: FontWeight.w600,),

                                          ],
                                        ),
                                        AppText(
                                          widget.patientProgressNote.createdOn !=null?DateUtils.getDayMonthYearDateFormatted(DateTime.parse(widget.patientProgressNote.createdOn)):DateUtils.getDayMonthYearDateFormatted(DateTime.now()),
                                          fontWeight: FontWeight
                                              .w600,
                                          fontSize: 14,
                                        )

                                      ],
                                    ),
                                    Row(

                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            AppText('Condition: ',
                                              fontSize: 12,),
                                            AppText(
                                                widget.patientProgressNote.mName??'',fontWeight: FontWeight.w600),
                                          ],
                                        ),
                                        AppText(
                                          widget.patientProgressNote.createdOn !=null?DateUtils.getHour(DateTime.parse(widget.patientProgressNote.createdOn)):DateUtils.getHour(DateTime.now()),
                                          fontWeight: FontWeight.w600,
                                          fontSize: 14,
                                        )
                                      ],
                                    ),
                                    SizedBox(height: 8,
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.start,
                                      children: [
                                        Expanded(
                                          child: AppText(
                                            progressNoteController.text,
                                            fontSize: 10,
                                          ),
                                        ),
                                        InkWell(
                                            onTap: (){
                                              setState(() {
                                                isAddProgress = true;
                                                widget.changePageViewIndex(3,isChangeState:false);
                                              });
                                            },
                                            child: Icon(DoctorApp.edit,size: 18,))
                                      ],
                                    ),
                                  ],
                                ),
                              )
                          ],
                        ),

                      ],
                    ),
                    isExpanded:  isProgressExpanded,
                  ),

                ],
              ),
            ),
          ),
        ),
       bottomSheet: Container(
         decoration: BoxDecoration(
           color: Colors.white,
           borderRadius: BorderRadius.all(
             Radius.circular(0.0),
           ),
           border: Border.all(
               color: HexColor('#707070'),
               width: 0),
         ),
         width: double.maxFinite,
         height: 90,
         child: Padding(
           padding: const EdgeInsets.all(8.0),
           child: Container(
             margin: EdgeInsets.all(6),
             child: Column(
               children: [
                 Row(
                   children: [
                     Expanded(
                       child: AppButton(
                         title: TranslationBase.of(context).previous,
                         color: Colors.grey[300],
                         fontColor: Colors.black,
                         fontWeight: FontWeight.w600,
                         onPressed: () async {
                           setState(() {
                             widget.changePageViewIndex(2);
                           });
                         },
                       ),
                     ),
                     SizedBox(width: 5,),
                     Expanded(
                       child: AppButton(
                         title: isAddProgress? TranslationBase.of(context).next: "Finish",
                         fontWeight: FontWeight.w600,
                         color: Colors.red[700],
                         loading: model.state == ViewState.BusyLocal,
                         disabled: progressNoteController.text.isEmpty,
                         onPressed: () async {
                            if (progressNoteController.text.isNotEmpty) {
                              if (isAddProgress) {
                                Map profile =
                                    await sharedPref.getObj(DOCTOR_PROFILE);
                                DoctorProfileModel doctorProfile =
                                    DoctorProfileModel.fromJson(profile);
                                setState(() {
                                  widget.patientProgressNote.createdByName =
                                      widget.patientProgressNote
                                              .createdByName ??
                                          doctorProfile.doctorName;
                                  widget.patientProgressNote.editedByName =
                                      doctorProfile.doctorName;
                                  widget.patientProgressNote.createdOn =
                                      DateTime.now().toString();
                                  widget.patientProgressNote.planNote =
                                      progressNoteController.text;
                                  isAddProgress = !isAddProgress;
                                });
                                submitPlan(model);
                              } else {
                                Navigator.of(context).pop();
                              }
                            } else {
                              Helpers.showErrorToast(TranslationBase.of(context)
                                  .progressNoteErrorMsg);
                            }
                          },
                       ),
                     ),
                   ],
                 ),

               ],
             ),
           ),
         ),
       ),
      ),
    );
  }

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

      if(model.patientProgressNoteList.isEmpty){
        await model.postProgressNote(postProgressNoteRequestModel);

      }else {
        Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

        DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
        postProgressNoteRequestModel.editedBy =doctorProfile.doctorID;
        await model.patchProgressNote(postProgressNoteRequestModel);

      }

      if (model.state == ViewState.ErrorLocal) {
        Helpers.showErrorToast(model.error);
      } else {
        widget.changePageViewIndex(4,isChangeState:false);
      }
    } else {
      Helpers.showErrorToast(TranslationBase.of(context).progressNoteErrorMsg);
    }
  }


}
