import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_assement.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/core/viewModel/project_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/shared_soap_widgets/remark_text.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/soap_utils.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:flutter/material.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';
import 'assessment_call_back.dart';

// ignore: must_be_immutable
class UpdateAssessmentPage extends StatefulWidget {
  final Function changePageViewIndex;
  final PatiantInformtion patientInfo;
  final Function changeLoadingState;
  final int currentIndex;

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

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

class _UpdateAssessmentPageState extends State<UpdateAssessmentPage> implements AssessmentCallBack {
  bool isAssessmentExpand = false;
  List<MySelectedAssessment> mySelectedAssessmentList = [];
  bool isPrescriptionOrder = false;

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        model.setAssessmentCallBack(this);
        mySelectedAssessmentList.clear();
        await model.isPrescriptionOrderCreated(widget.patientInfo);
        await model.onUpdateAssessmentStepStart(widget.patientInfo);

        if (model.patientAssessmentList.isNotEmpty) {
          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 = SoapUtils.generateMySelectedAssessment(
                  appointmentNo: element.appointmentNo,
                  remark: element.remarks,
                  diagnosisType: diagnosisType,
                  diagnosisCondition: diagnosisCondition,
                  selectedICD: selectedICD,
                  doctorID: element.doctorID,
                  doctorName: element.doctorName,
                  createdBy: element.createdBy,
                  createdOn: element.createdOn,
                  icdCode10ID: element.icdCode10ID);

              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,
                      patientInfo: widget.patientInfo,
                    ),
                    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: mySelectedAssessmentList.map((assessment) {
                                return Container(
                                  margin: EdgeInsets.only(left: 5, right: 5, top: 15, bottom: 15),
                                  child: Column(
                                    children: [
                                      Row(
                                        children: [
                                          RichText(
                                            text: new TextSpan(
                                              style: new TextStyle(
                                                  fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                  color: Color(0xFF2E303A),
                                                  fontFamily: 'Poppins',
                                                  fontWeight: FontWeight.w600,
                                                  letterSpacing: -0.4),
                                              children: <TextSpan>[
                                                new TextSpan(
                                                  text: "ICD : ".toUpperCase(),
                                                ),
                                                new TextSpan(text: (assessment != null && assessment.selectedICD != null) ? assessment.selectedICD!.code.trim().toUpperCase() ?? "" : ""),
                                              ],
                                            ),
                                          ),
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              AppText(
                                                assessment.createdOn != null
                                                    ? AppDateUtils.getDayMonthYearDateFormatted(DateTime.parse(assessment.createdOn!), isMonthShort: true)
                                                    : AppDateUtils.getDayMonthYearDateFormatted(DateTime.now()),
                                                fontWeight: FontWeight.w600,
                                                fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                              ),
                                              AppText(
                                                assessment.createdOn != null ? AppDateUtils.getHour(DateTime.parse(assessment.createdOn!)) : AppDateUtils.getHour(DateTime.now()),
                                                fontWeight: FontWeight.w600,
                                                color: Color(0xFF575757),
                                                fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                              ),
                                            ],
                                          ),
                                        ],
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                      ),
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Container(
                                                width: MediaQuery.of(context).size.width * 0.50,
                                                child: RichText(
                                                  text: new TextSpan(
                                                    style: new TextStyle(
                                                      fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 4.3,
                                                      color: Color(0xFF2E303A),
                                                      fontFamily: 'Poppins',
                                                      fontWeight: FontWeight.w600,
                                                      letterSpacing: -0.64,
                                                    ),
                                                    children: <TextSpan>[
                                                      new TextSpan(
                                                        text: (assessment != null && assessment.selectedICD != null) ? assessment.selectedICD!.description.toString() : "",
                                                        // text: assessment.selectedICD.description.toString(),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                              RichText(
                                                text: new TextSpan(
                                                  style: new TextStyle(
                                                    fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.5,
                                                    color: Color(0xFF2E303A),
                                                    fontFamily: 'Poppins',
                                                    fontWeight: FontWeight.w600,
                                                  ),
                                                  children: <TextSpan>[
                                                    new TextSpan(
                                                      text: TranslationBase.of(context).appointmentNo,
                                                      style: new TextStyle(
                                                        fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3,
                                                        letterSpacing: -0.4,
                                                        color: Color(0xFF575757),
                                                      ),
                                                    ),
                                                    new TextSpan(
                                                      text: assessment.appointmentId.toString() ?? "",
                                                      style: new TextStyle(
                                                        fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                        letterSpacing: -0.48,
                                                        color: Color(0xFF2B353E),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              RichText(
                                                text: new TextSpan(
                                                  style: new TextStyle(
                                                      fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3, color: Color(0xFF2E303A), fontFamily: 'Poppins', fontWeight: FontWeight.w600),
                                                  children: <TextSpan>[
                                                    new TextSpan(
                                                      text: TranslationBase.of(context).condition + " : ",
                                                      style: new TextStyle(
                                                        letterSpacing: -0.4,
                                                        color: Color(0xFF575757),
                                                      ),
                                                    ),
                                                    new TextSpan(
                                                      text: projectViewModel.isArabic ? assessment.selectedDiagnosisCondition!.nameAr : assessment.selectedDiagnosisCondition!.nameEn,
                                                      style: new TextStyle(
                                                        fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                        letterSpacing: -0.48,
                                                        color: Color(0xFF2B353E),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              RichText(
                                                text: new TextSpan(
                                                  style: new TextStyle(
                                                      fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3, color: Color(0xFF2E303A), fontFamily: 'Poppins', fontWeight: FontWeight.w600),
                                                  children: <TextSpan>[
                                                    new TextSpan(
                                                      text: TranslationBase.of(context).dType + ' : ',
                                                      style: new TextStyle(
                                                        letterSpacing: -0.4,
                                                        color: Color(0xFF575757),
                                                      ),
                                                    ),
                                                    new TextSpan(
                                                      text: projectViewModel.isArabic ? assessment.selectedDiagnosisType!.nameAr : assessment.selectedDiagnosisType!.nameEn,
                                                      style: new TextStyle(
                                                        fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                        letterSpacing: -0.48,
                                                        color: Color(0xFF2B353E),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              if (assessment.doctorName != null)
                                                RichText(
                                                  text: new TextSpan(
                                                    style: new TextStyle(
                                                        fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6, color: Color(0xFF2E303A), fontFamily: 'Poppins', fontWeight: FontWeight.w600),
                                                    children: <TextSpan>[
                                                      new TextSpan(
                                                        text: TranslationBase.of(context).doctor + ' : ',
                                                        style: new TextStyle(
                                                          fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3,
                                                          letterSpacing: -0.4,
                                                          color: Color(0xFF575757),
                                                        ),
                                                      ),
                                                      new TextSpan(
                                                        text: assessment.doctorName ?? '',
                                                        style: new TextStyle(
                                                          fontSize: SizeConfig.getTextMultiplierBasedOnWidth() * 3.6,
                                                          letterSpacing: -0.48,
                                                          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: SizeConfig.getTextMultiplierBasedOnWidth() * 3, color: Color(0xFF2E303A), fontFamily: 'Poppins', fontWeight: FontWeight.w600),
                                                  RemarkText(
                                                    remark: assessment.remark ?? "",
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              SizedBox(
                                                height: MediaQuery.of(context).size.height * 0.05,
                                              ),
                                              InkWell(
                                                onTap: () {
                                                  if (model.isPrescriptionOrder && assessment.selectedDiagnosisType!.id == 2) {
                                                    Utils.showErrorToast(TranslationBase.of(context).principalDiagnosisCannot);
                                                  } else {
                                                    openAssessmentDialog(context, isUpdate: true, assessment: assessment, model: model);
                                                  }
                                                },
                                                child: Icon(
                                                  DoctorApp.edit,
                                                  size: 18,
                                                  color: model.isPrescriptionOrder && assessment.selectedDiagnosisType!.id == 2 ? Colors.grey : Colors.black,
                                                ),
                                              )
                                            ],
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                );
                              }).toList(),
                            )
                          ],
                        )
                      ]),
                      isExpanded: isAssessmentExpand,
                    ),
                    SizedBox(
                      height: 130,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

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

  @override
  nextFunction(model) {
    if (mySelectedAssessmentList.isEmpty) {
      Utils.showErrorToast(TranslationBase.of(context).assessmentErrorMsg);
    } else if (!checkPrimaryDiagnosis()) {
      Utils.showErrorToast(TranslationBase.of(context).onePrimaryDiagnosis);
    } else {
      widget.changeLoadingState(true);
      widget.changePageViewIndex(3);
    }
  }

  bool checkPrimaryDiagnosis() {
    ProjectViewModel projectViewModel = Provider.of<ProjectViewModel>(context, listen: false);
    bool isVidaPlus = Utils.isVidaPlusProject(projectViewModel, widget.patientInfo.projectId!);
    List<MySelectedAssessment> type =
        mySelectedAssessmentList.where((element) => (element.selectedDiagnosisType!.id == 2 && isVidaPlus == false) || (element.selectedDiagnosisType!.code == '3' && isVidaPlus == true)).toList();
    return type.isEmpty ? false : true;
  }
}
