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/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/my_selected_assement.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:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.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_assessment_details.dart';

// ignore: must_be_immutable
class UpdateAssessmentPage extends StatefulWidget {
  final Function changePageViewIndex;
  List<MySelectedAssessment> mySelectedAssessmentList;
  final PatiantInformtion patientInfo;
  final Function changeLoadingState;
  final int  currentIndex;
  UpdateAssessmentPage(
      {Key key,
      this.changePageViewIndex,
      this.mySelectedAssessmentList,
      this.patientInfo,
      this.changeLoadingState, this.currentIndex});

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

class _UpdateAssessmentPageState extends State<UpdateAssessmentPage> {
  bool isAssessmentExpand = false;
  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        widget.mySelectedAssessmentList.clear();
        GetAssessmentReqModel getAssessmentReqModel = GetAssessmentReqModel(
            patientMRN: widget.patientInfo.patientMRN,
            episodeID: widget.patientInfo.episodeNo.toString(),
            editedBy: '',
            doctorID: '',
            appointmentNo: widget.patientInfo.appointmentNo);
        await model.getPatientAssessment(getAssessmentReqModel);
        if (model.patientAssessmentList.isNotEmpty) {
          if (model.listOfDiagnosisCondition.length == 0) {
            await model.getMasterLookup(MasterKeysService.DiagnosisCondition);
          }
          if (model.listOfDiagnosisType.length == 0) {
            await model.getMasterLookup(MasterKeysService.DiagnosisType);
          }
          if (model.listOfICD10.length == 0) {
            await model.getMasterLookup(MasterKeysService.ICD10);
          }
          model.patientAssessmentList.forEach((element) {
            MasterKeyModel diagnosisType = model.getOneMasterKey(
              masterKeys: MasterKeysService.DiagnosisType,
              id: element.diagnosisTypeID,
            );
            MasterKeyModel selectedICD = model.getOneMasterKey(
              masterKeys: MasterKeysService.ICD10,
              id: element.icdCode10ID,
            );
            MasterKeyModel diagnosisCondition = model.getOneMasterKey(
              masterKeys: MasterKeysService.DiagnosisCondition,
              id: element.conditionID,
            );
            if (diagnosisCondition != null &&
                diagnosisType != null &&
                diagnosisCondition != null) {
              MySelectedAssessment temMySelectedAssessment =
                  MySelectedAssessment(
                      appointmentId: element.appointmentNo,
                      remark: element.remarks,
                      selectedDiagnosisType: diagnosisType,
                      selectedDiagnosisCondition: diagnosisCondition,
                      selectedICD: selectedICD,
                      doctorID: element.doctorID,
                      doctorName: element.doctorName,
                      createdBy: element.createdBy,
                      createdOn: element.createdOn,
                      icdCode10ID: element.icdCode10ID);

              widget.mySelectedAssessmentList.add(temMySelectedAssessment);
            }
          });
        }

        widget.changeLoadingState(false);
      },
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: false,
        backgroundColor: Theme
            .of(context)
            .scaffoldBackgroundColor,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Container(

            color: Theme
                .of(context)
                .scaffoldBackgroundColor,
            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).assessment
                      ,
                      onTap: () {
                        setState(() {
                          isAssessmentExpand = !isAssessmentExpand;
                        });
                      },
                      child: Column(children: [
                        SizedBox(
                          height: 20,
                        ),
                        Column(
                          children: [

                            SOAPOpenItems(label: "${TranslationBase.of(context).addAssessment}",onTap: () {
                              openAssessmentDialog(context,
                                  isUpdate: false, model: model);
                            },),

                            SizedBox(
                              height: 20,
                            ),
                            Column(
                              children: widget.mySelectedAssessmentList
                                  .map((assessment) {
                                return Container(
                                  margin: EdgeInsets.only(
                                      left: 5, right: 5, top: 15),
                                  child: Row(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: [
                                      Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: [
                                          RichText(
                                            text: new TextSpan(
                                              style: new TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF2E303A),
                                                  fontFamily: 'Poppins',
                                                  fontWeight: FontWeight.w600),
                                              children: <TextSpan>[
                                                new TextSpan(
                                                  text: "ICD : ".toUpperCase(),
                                                ),
                                                new TextSpan(
                                                  text: assessment
                                                          .selectedICD.code
                                                          .trim()
                                                          .toUpperCase() ??
                                                      "",
                                                ),
                                              ],
                                            ),
                                          ),
                                          Container(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                0.50,
                                            child: RichText(
                                              text: new TextSpan(
                                                style: new TextStyle(
                                                    fontSize: 16,
                                                    color: Color(0xFF2E303A),
                                                    fontFamily: 'Poppins',
                                                    fontWeight:
                                                        FontWeight.w600),
                                                children: <TextSpan>[
                                                  new TextSpan(
                                                    text: assessment
                                                        .selectedICD.description
                                                        .toString(),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          RichText(
                                            text: new TextSpan(
                                              style: new TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF2E303A),
                                                  fontFamily: 'Poppins',
                                                  fontWeight: FontWeight.w600),
                                              children: <TextSpan>[
                                                new TextSpan(
                                                  text: TranslationBase.of(
                                                          context)
                                                      .appointmentNo,
                                                  style: new TextStyle(
                                                    color: Color(0xFF575757),
                                                  ),
                                                ),
                                                new TextSpan(
                                                  text: assessment
                                                          .appointmentId.toString()

                                                           ??
                                                      "",
                                                  style: new TextStyle(
                                                    fontSize: 14,
                                                    color: Color(0xFF2B353E),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          RichText(
                                            text: new TextSpan(
                                              style: new TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF2E303A),
                                                  fontFamily: 'Poppins',
                                                  fontWeight: FontWeight.w600),
                                              children: <TextSpan>[
                                                new TextSpan(
                                                  text: TranslationBase.of(
                                                              context)
                                                          .condition +
                                                      " : ",
                                                  style: new TextStyle(
                                                    color: Color(0xFF575757),
                                                  ),
                                                ),
                                                new TextSpan(
                                                  text: projectViewModel
                                                          .isArabic
                                                      ? assessment
                                                          .selectedDiagnosisCondition
                                                          .nameAr
                                                      : assessment
                                                          .selectedDiagnosisCondition
                                                          .nameEn,
                                                  style: new TextStyle(
                                                    fontSize: 14,
                                                    color: Color(0xFF2B353E),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          RichText(
                                            text: new TextSpan(
                                              style: new TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFF2E303A),
                                                  fontFamily: 'Poppins',
                                                  fontWeight: FontWeight.w600),
                                              children: <TextSpan>[
                                                new TextSpan(
                                                  text: TranslationBase.of(
                                                              context)
                                                          .dType +
                                                      ' : ',
                                                  style: new TextStyle(
                                                    color: Color(0xFF575757),
                                                  ),
                                                ),
                                                new TextSpan(
                                                  text: projectViewModel
                                                          .isArabic
                                                      ? assessment
                                                          .selectedDiagnosisType
                                                          .nameAr
                                                      : assessment
                                                          .selectedDiagnosisType
                                                          .nameEn,
                                                  style: new TextStyle(
                                                    fontSize: 14,
                                                    color: Color(0xFF2B353E),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          if (assessment.doctorName != null)
                                            RichText(
                                              text: new TextSpan(
                                                style: new TextStyle(
                                                    fontSize: 12,
                                                    color: Color(0xFF2E303A),
                                                    fontFamily: 'Poppins',
                                                    fontWeight:
                                                        FontWeight.w600),
                                                children: <TextSpan>[
                                                  new TextSpan(
                                                    text: TranslationBase.of(
                                                                context)
                                                            .doc +
                                                        ' : ',
                                                    style: new TextStyle(
                                                      color: Color(0xFF575757),
                                                    ),
                                                  ),
                                                  new TextSpan(
                                                    text:
                                                        assessment.doctorName ??
                                                            '',
                                                    style: new TextStyle(
                                                      fontSize: 14,
                                                      color: Color(0xFF2B353E),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          SizedBox(
                                            height: 6,
                                          ),

                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              SizedBox(
                                                height: 6,
                                              ),
                                              AppText(
                                                (assessment.remark != null ||
                                                    assessment.remark !=
                                                        '')
                                                    ? TranslationBase.of(
                                                    context)
                                                    .remarks +
                                                    " : "
                                                    : '',

                                                fontSize: 12,
                                                color: Color(0xFF2E303A),
                                                fontFamily: 'Poppins',
                                                fontWeight:
                                                FontWeight.w600
                                              ),
                                              Container(
                                                width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                    0.38,
                                                child: AppText(
                                                  assessment.remark ?? "",
                                                  fontSize: 11,
                                                  color: Color(0xFF2B353E),
                                                  fontWeight: FontWeight.w700,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                      Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.end,
                                        children: [
                                          Row(
                                            children: [
                                              Column(
                                                children: [
                                                  AppText(
                                                    assessment.createdOn != null
                                                        ? DateUtils
                                                        .getDayMonthYearDateFormatted(
                                                        DateTime.parse(
                                                            assessment
                                                                .createdOn))
                                                        : DateUtils
                                                        .getDayMonthYearDateFormatted(
                                                        DateTime.now()),
                                                    fontWeight: FontWeight
                                                        .w600,
                                                    fontSize: 14,
                                                  ), AppText(
                                                    assessment.createdOn != null
                                                        ? DateUtils.getHour(
                                                        DateTime.parse(
                                                            assessment
                                                                .createdOn))
                                                        : DateUtils.getHour(
                                                        DateTime.now()),
                                                    fontWeight: FontWeight
                                                        .w600,
                                                    fontSize: 14,
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: MediaQuery.of(context)
                                                .size
                                                .height *
                                                0.05,
                                          ),
                                          InkWell(
                                            onTap: () {
                                              openAssessmentDialog(context,
                                                  isUpdate: true,
                                                  assessment: assessment,
                                                  model: model);
                                            },
                                            child: Icon(
                                              DoctorApp.edit, size: 18,),
                                          )
                                        ],
                                      ),
                                    ],
                                  ),
                                );
                              }).toList(),
                            )
                          ],
                        )
                      ]),
                      isExpanded:  isAssessmentExpand,
                    ),
                    SizedBox(
                      height: 130,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        bottomSheet: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(0.0),
            ),
            border: Border.all(
                color: HexColor('#707070'),
                width: 0),
          ),          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              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,
                    loading: model.state == ViewState.BusyLocal,
                    onPressed: () async {
                      widget.changePageViewIndex(1);
                    },
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * 0.05,
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.4,
                  child: AppButton(
                    title: TranslationBase
                        .of(context)
                        .next,
                    fontWeight: FontWeight.w600,
                    color: Colors.red[700],
                    loading: model.state == ViewState.BusyLocal,
                    onPressed: () async {
                      if (widget.mySelectedAssessmentList.isEmpty) {
                        Helpers.showErrorToast(
                            TranslationBase
                                .of(context)
                                .assessmentErrorMsg);
                      } else {
                        widget.changePageViewIndex(3);
                        widget.changeLoadingState(true);
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  openAssessmentDialog(BuildContext context,
      {MySelectedAssessment assessment, bool isUpdate, SOAPViewModel model}) {
    if (assessment == null) {
      assessment = MySelectedAssessment(
          remark: '', appointmentId: widget.patientInfo.appointmentNo);
    }
    showModalBottomSheet(
        backgroundColor: Colors.white,
        isScrollControlled: true,
        context: context,
        builder: (context) {
          return AddAssessmentDetails(
              mySelectedAssessment: assessment,
              patientInfo: widget.patientInfo,
              isUpdate: isUpdate,
              mySelectedAssessmentList: widget.mySelectedAssessmentList,
              addSelectedAssessment: (MySelectedAssessment mySelectedAssessment,
                  bool isUpdate) async {
                setState(() {
                  widget.mySelectedAssessmentList.add(mySelectedAssessment);
                });
              });
        });
  }
}

