import 'package:doctor_app_flutter/config/config.dart';
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/viewstate.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_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/Text.dart';
import 'package:doctor_app_flutter/widgets/shared/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/app-textfield-custom.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.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/divider_with_spaces_around.dart';
import 'package:doctor_app_flutter/widgets/shared/expandable-widget-header-body.dart';
import 'package:doctor_app_flutter/widgets/shared/new_text_Field.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

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

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

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

class _UpdatePlanPageState extends State<UpdatePlanPage> {
  bool isAddProgress = 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(
        // baseViewModel: model,
        backgroundColor: Colors.grey[200],
        isShowAppBar: false,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Center(
            child: FractionallySizedBox(
              widthFactor: 0.95,
              child: Container(
                margin: EdgeInsets.all(8.0),
                padding: EdgeInsets.all(12.0),
                decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  border: Border.fromBorderSide(BorderSide(
                    color: Colors.grey.shade400,
                    width: 0.4,
                  )),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            margin: EdgeInsets.only(left: 5, right: 5),
                            child: Texts(TranslationBase.of(context).progressNote)),
                        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: [
                                        Texts('Appointment No: ',fontSize: 12,),
                                        Texts(widget.patientProgressNote.appointmentNo??'',fontWeight: FontWeight.w600,),

                                      ],
                                    ),
                                    Texts(
                                      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: [
                                        Texts('Condition: ',fontSize: 12,),
                                        Texts(widget.patientProgressNote.mName??'',fontWeight: FontWeight.w600),
                                      ],
                                    ),
                                    Texts(
                                      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: Texts(
                                        progressNoteController.text,
                                        fontSize: 10,

                                      ),
                                    ),
                                    InkWell(
                                        onTap: (){
                                          setState(() {
                                            isAddProgress = true;
                                            widget.changePageViewIndex(3,isChangeState:false);
                                          });
                                        },
                                        child: Icon(DoctorApp.edit,size: 18,))
                                  ],
                                ),
                              ],
                            ),
                          )
                      ],
                    ),

                  ],
                ),
              ),
            ),
          ),
        ),
       bottomSheet: Container(
         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: 'Previous',
                         color: Colors.grey[300],
                         fontColor: Colors.black,
                         fontWeight: FontWeight.w400,
                         loading: model.state == ViewState.BusyLocal,
                         onPressed: () async {
                           setState(() {
                             widget.changePageViewIndex(2);
                           });
                         },
                       ),
                     ),
                     SizedBox(width: 5,),
                     Expanded(
                       child: AppButton(
                         title: isAddProgress? TranslationBase.of(context).next: "Finish",
                         fontWeight: FontWeight.w400,
                         loading: model.state == ViewState.BusyLocal,
                         color: Colors.red[700],
                         disabled: progressNoteController.text.isEmpty,
                         onPressed: () async {

                           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();
                           }
                         },
                       ),
                     ),
                   ],
                 ),

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

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


}
