import 'package:autocomplete_textfield/autocomplete_textfield.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/view_state.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/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/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.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/bottom_sheet/custom_bottom_sheet_container.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/dialogs/master_key_dailog.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../../../core/model/SOAP/Assessment/post_assessment_request_model.dart';
import '../../../../../core/model/SOAP/assessment/patch_assessment_req_model.dart';

class AddAssessmentDetails extends StatefulWidget {
  final MySelectedAssessment mySelectedAssessment;
  final List<MySelectedAssessment> mySelectedAssessmentList;
  final Function(MySelectedAssessment mySelectedAssessment, bool isUpdate) addSelectedAssessment;
  final PatiantInformtion patientInfo;
  final bool isUpdate;

  AddAssessmentDetails({Key? key, required this.mySelectedAssessment, required this.addSelectedAssessment, required this.patientInfo, this.isUpdate = false, required this.mySelectedAssessmentList});

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

class _AddAssessmentDetailsState extends State<AddAssessmentDetails> {
  TextEditingController remarkController = TextEditingController();
  TextEditingController appointmentIdController = TextEditingController();
  TextEditingController conditionController = TextEditingController();
  TextEditingController typeController = TextEditingController();
  TextEditingController icdNameController = TextEditingController();

  GlobalKey key = new GlobalKey<AutoCompleteTextFieldState<MasterKeyModel>>();
  bool isFormSubmitted = false;
  bool complexDiagnosis = true;

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

    remarkController.text = widget.mySelectedAssessment.remark ?? "";
    appointmentIdController.text = widget.mySelectedAssessment.appointmentId.toString();
    if (widget.isUpdate) {
      if (widget.mySelectedAssessment.selectedDiagnosisCondition != null)
        conditionController.text = projectViewModel.isArabic ? widget.mySelectedAssessment.selectedDiagnosisCondition!.nameAr! : widget.mySelectedAssessment.selectedDiagnosisCondition!.nameEn!;
      if (widget.mySelectedAssessment.selectedDiagnosisType != null)
        typeController.text = projectViewModel.isArabic ? widget.mySelectedAssessment.selectedDiagnosisType!.nameAr! : widget.mySelectedAssessment.selectedDiagnosisType!.nameEn!;
      if (widget.mySelectedAssessment.selectedICD != null) icdNameController.text = widget.mySelectedAssessment.selectedICD!.code;
    }
    InputDecoration textFieldSelectorDecoration(String hintText, String? selectedText, bool isDropDown, {IconData? icon, String? validationError}) {
      return new InputDecoration(
        fillColor: Colors.white,
        contentPadding: EdgeInsets.symmetric(vertical: 15, horizontal: 10),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: (validationError != null ? Colors.red.shade700 : Color(0xFFEFEFEF)), width: 2.5),
          borderRadius: BorderRadius.circular(8),
        ),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: (validationError != null ? Colors.red.shade700 : Color(0xFFEFEFEF)), width: 2.5),
          borderRadius: BorderRadius.circular(8),
        ),
        disabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: (validationError != null ? Colors.red.shade700 : Color(0xFFEFEFEF)), width: 2.5),
          borderRadius: BorderRadius.circular(8),
        ),
        hintText: selectedText != null ? selectedText : hintText,
        suffixIcon: isDropDown ? Icon(icon ?? Icons.arrow_drop_down) : null,
        filled: true,
        hintStyle: TextStyle(
          fontSize: 10,
          color: Colors.grey.shade600,
        ),
      );
    }

    return FractionallySizedBox(
      heightFactor: 1,
      child: BaseView<SOAPViewModel>(
        onModelReady: (model) async {
          // model.callAddAssessmentLookupsServices();
        },
        builder: (_, model, w) => AppScaffold(
          baseViewModel: model,
          isShowAppBar: true,
          appBar: BottomSheetTitle(title: widget.isUpdate ? TranslationBase.of(context).updateAssessmentDetails : TranslationBase.of(context).addAssessmentDetails),
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body: SingleChildScrollView(
            child: Center(
              child: Column(
                children: [
                  FractionallySizedBox(
                    widthFactor: 0.9,
                    child: Container(
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      SizedBox(
                        height: 16,
                      ),
                      Row(children: [
                        Checkbox(
                          value: complexDiagnosis,
                          onChanged: (bool? value) {
                            complexDiagnosis = value!;
                            setState(() {});
                          },
                          checkColor: Colors.white,
                          activeColor: Colors.green,
                        ),
                        Text(
                          TranslationBase.of(context).complexDiagnosis,
                        ),
                      ]),
                      SizedBox(
                        height: 16,
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 0, right: 0, top: 15),
                        child: AppTextFieldCustom(
                          // height: 55.0,
                          height: Utils.getTextFieldHeight(),
                          hintText: TranslationBase.of(context).appointmentNumber,
                          isTextFieldHasSuffix: false,
                          enabled: false,
                          controller: appointmentIdController,
                          onChanged: (value) {},
                          onFieldSubmitted: () {},
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Column(children: [
                        InkWell(
                            onTap: model.listOfICD10 != null
                                ? () {
                                    setState(() {
                                      widget.mySelectedAssessment.selectedICD = null;
                                      icdNameController.text = 'null';
                                    });
                                  }
                                : null,
                            child: AppTextFieldCustom(
                              onChanged: (text) {
                                setState(() {
                                  icdNameController.text;
                                });
                              },
                              height: Utils.getTextFieldHeight(),
                              onClick: model.listOfICD10 != null
                                  ? () {
                                      setState(() {
                                        widget.mySelectedAssessment.selectedICD = null;
                                        icdNameController.text = 'null';
                                      });
                                    }
                                  : null,
                              hintText: TranslationBase.of(context).nameOrICD,
                              maxLines: 1,
                              minLines: 1,
                              controller: icdNameController,
                              enabled: true,
                              isTextFieldHasSuffix: true,
                              suffixIcon: IconButton(
                                  onPressed: () {
                                    if (icdNameController.text.length <= 2) {
                                      DrAppToastMsg.showErrorToast("Please enter 3 or more characters");
                                    } else {
                                      model.listOfICD10!.clear();
                                      model.callAddAssessmentLookupsServices(searchKey: icdNameController.text);
                                    }
                                  },
                                  icon: Icon(
                                    Icons.search,
                                    color: Colors.grey.shade600,
                                  )),
                              onFieldSubmitted: () {},
                            )),

                        model.listOfICD10.length > 0 && icdNameController.text.isNotEmpty
                            ? Container(
                                color: Colors.white,
                                height: MediaQuery.of(context).size.height * 0.4, //height to 9% of screen height,
                                child: ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: model.listOfICD10.length,
                                  itemBuilder: (context, index) {
                                    return InkWell(
                                        child: ListTile(title: AppText(model.listOfICD10[index].description + " / " + model.listOfICD10[index].code.toString(), fontSize: 12.0)),
                                        onTap: () {
                                          widget.mySelectedAssessment.selectedICD = model.listOfICD10[index];
                                          icdNameController.text = model.listOfICD10[index].description;
                                          model.listOfICD10.clear();
                                          setState(() {});
                                        });
                                  },
                                ))
                            : SizedBox()
                        // CustomAutoCompleteTextField(
                        //         isShowError: isFormSubmitted && widget.mySelectedAssessment.selectedICD == null,
                        //         child: Row(
                        //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        //           mainAxisSize: MainAxisSize.min,
                        //           children: [
                        //             AutoCompleteTextField<MasterKeyModel>(
                        //                 decoration: TextFieldsUtils.textFieldSelectorDecoration(TranslationBase.of(context).nameOrICD, null, true, suffixIcon: null),
                        //                 controller: icdNameController,
                        //                 itemSubmitted: (item) => setState(() {
                        //                   widget.mySelectedAssessment.selectedICD = item;
                        //                   // icdNameController.text = '${item.code.trim()}/${item.description}';
                        //                   icdNameController.text = '${item.description}';
                        //                 }),
                        //                 key: key,
                        //                 suggestions: model.listOfICD10,
                        //                 suggestionsAmount: model.listOfICD10.length,
                        //                 itemBuilder: (context, suggestion) =>
                        //                     new Padding(child: AppText(suggestion.description + " / " + suggestion.code.toString(), fontSize: 12.0), padding: EdgeInsets.all(8.0)),
                        //                 itemSorter: (a, b) => 1,
                        //                 itemFilter: (suggestion, input) =>
                        //                     // suggestion.description.toLowerCase().startsWith(input.toLowerCase()) ||
                        //                     // suggestion.description.toLowerCase().startsWith(input.toLowerCase()) ||
                        //                     // suggestion.code.toLowerCase().startsWith(input.toLowerCase()),
                        //                     suggestion.description.toLowerCase().contains(input.toLowerCase()) ||
                        //                     // suggestion.description.toLowerCase().startsWith(input.toLowerCase()) ||
                        //                     suggestion.code.toLowerCase().contains(input.toLowerCase()),
                        //
                        //             ),
                        //             Expanded(
                        //               child: IconButton(
                        //                 onPressed: () {
                        //                   print(icdNameController.text);
                        //                   if (icdNameController.text.length <= 3) {
                        //                     DrAppToastMsg.showErrorToast("Please enter 4 or more characters");
                        //                   } else {
                        //                     model.listOfICD10.clear();
                        //                     model.callAddAssessmentLookupsServices(searchKey: icdNameController.text);
                        //                   }
                        //                 },
                        //                 icon: Icon(Icons.search),
                        //               ),
                        //             ),
                        //           ],
                        //         ),
                        //       )
                      ]),
                      if (widget.mySelectedAssessment.selectedICD != null)
                        Column(
                          children: [
                            SizedBox(
                              height: 3,
                            ),
                            Container(
                              width: MediaQuery.of(context).size.width * 0.7,
                              child: AppText(
                                widget.mySelectedAssessment.selectedICD!.description + (' (${widget.mySelectedAssessment.selectedICD!.code} )'),
                                color: Color(0xFF575757),
                                fontSize: 10,
                                fontWeight: FontWeight.w700,
                                letterSpacing: -0.4,
                              ),
                            ),
                          ],
                        ),
                      SizedBox(
                        height: 7,
                      ),
                      AppTextFieldCustom(
                        height: Utils.getTextFieldHeight(),
                        onClick: model.listOfDiagnosisCondition != null
                            ? () {
                                MasterKeyDailog dialog = MasterKeyDailog(
                                  list: model.listOfDiagnosisCondition!,
                                  okText: TranslationBase.of(context).ok,
                                  selectedValue: widget.mySelectedAssessment.selectedDiagnosisCondition,
                                  okFunction: (MasterKeyModel selectedValue) {
                                    setState(() {
                                      widget.mySelectedAssessment.selectedDiagnosisCondition = selectedValue;
                                      conditionController.text =
                                          projectViewModel.isArabic ? widget.mySelectedAssessment.selectedDiagnosisCondition!.nameAr! : widget.mySelectedAssessment.selectedDiagnosisCondition!.nameEn!;
                                    });
                                  },
                                );
                                showDialog(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dialog;
                                  },
                                );
                              }
                            : null,
                        hintText: TranslationBase.of(context).condition,
                        maxLines: 1,
                        minLines: 1,
                        controller: conditionController,
                        isTextFieldHasSuffix: true,
                        enabled: false,
                        hasBorder: true,
                        validationError: isFormSubmitted && widget.mySelectedAssessment.selectedDiagnosisCondition == null ? TranslationBase.of(context).emptyMessage : null,
                        onChanged: (value) {},
                        onFieldSubmitted: () {},
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      AppTextFieldCustom(
                        height: Utils.getTextFieldHeight(),
                        onClick: model.listOfDiagnosisType != null
                            ? () {
                                MasterKeyDailog dialog = MasterKeyDailog(
                                  list: model.listOfDiagnosisType!,
                                  okText: TranslationBase.of(context).ok,
                                  selectedValue: widget.mySelectedAssessment.selectedDiagnosisType !=null ?  widget.mySelectedAssessment.selectedDiagnosisType : null,
                                  okFunction: (MasterKeyModel selectedValue) {
                                    setState(() {
                                      widget.mySelectedAssessment.selectedDiagnosisType = selectedValue;
                                      typeController.text = projectViewModel.isArabic ? selectedValue.nameAr! : selectedValue.nameEn!;
                                    });
                                  },
                                );
                                showDialog(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dialog;
                                  },
                                );
                              }
                            : null,
                        hintText: TranslationBase.of(context).dType,
                        maxLines: 1,
                        minLines: 1,
                        enabled: true,
                        isTextFieldHasSuffix: true,
                        controller: typeController,
                        hasBorder: true,
                        validationError: isFormSubmitted && widget.mySelectedAssessment.selectedDiagnosisType == null ? TranslationBase.of(context).emptyMessage : null,
                        onChanged: (value) {},
                        onFieldSubmitted: () {},
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 0, right: 0, top: 15),
                        child: AppTextFieldCustom(
                          hintText: TranslationBase.of(context).remarks,
                          maxLines: 18,
                          minLines: 5,
                          inputType: TextInputType.multiline,
                          controller: remarkController,
                          onChanged: (value) {
                            widget.mySelectedAssessment.remark = remarkController.text;
                          },
                          onFieldSubmitted: () {},
                        ),
                      ),
                      SizedBox(
                        height: SizeConfig.heightMultiplier! *
                            (SizeConfig.isHeightVeryShort
                                ? 20
                                : SizeConfig.isHeightShort
                                    ? 15
                                    : 10),
                      ),
                    ])),
                  ),
                ],
              ),
            ),
          ),
          bottomSheet: model.state == ViewState.Busy
              ? Container(
                  height: 0,
                )
              : CustomBottomSheetContainer(
                  label: (widget.isUpdate ? TranslationBase.of(context).updateAssessmentDetails : TranslationBase.of(context).addAssessmentDetails),
                  onTap: () async {
                    setState(() {
                      isFormSubmitted = true;
                    });
                    widget.mySelectedAssessment.remark = remarkController.text;
                    widget.mySelectedAssessment.appointmentId = int.parse(appointmentIdController.text);
                    if (widget.mySelectedAssessment.selectedDiagnosisCondition != null &&
                        widget.mySelectedAssessment.selectedDiagnosisType != null &&
                        widget.mySelectedAssessment.selectedICD != null) {
                      await submitAssessment(isUpdate: widget.isUpdate, model: model, mySelectedAssessment: widget.mySelectedAssessment);
                    }
                  },
                ),
        ),
      ),
    );
  }

  submitAssessment({SOAPViewModel? model, MySelectedAssessment? mySelectedAssessment, bool isUpdate = false}) async {
    Map<String, dynamic> profile = await sharedPref.getObj(DOCTOR_PROFILE);
    DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
    GifLoaderDialogUtils.showMyDialog(context);
    if (isUpdate) {
      PostAssessmentRequestUpdateModel patchAssessmentReqModel = PostAssessmentRequestUpdateModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeId: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          createdByName: doctorProfile.doctorName,
          createdBy: doctorProfile.doctorID,
          icdCodeDetails: [
            new IcdCodeDetailsUpdate(
                remarks: mySelectedAssessment!.remark,
                complexDiagnosis: complexDiagnosis,
                conditionId: mySelectedAssessment!.selectedDiagnosisCondition!.id,
                prevIcdCode10ID: mySelectedAssessment.icdCode10ID,
                diagnosisTypeId: mySelectedAssessment.selectedDiagnosisType!.id,
                icdcode10Id: mySelectedAssessment.selectedICD!.code)
          ]);

      await model?.patchAssessment(patchAssessmentReqModel);
    } else {
      // Map profile = await sharedPref.getObj(DOCTOR_PROFILE);
      // DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
      PostAssessmentRequestModel postAssessmentRequestModel = new PostAssessmentRequestModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeId: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          createdByName: doctorProfile.doctorName,
          createdBy: doctorProfile.doctorID,
          icdCodeDetails: [
            new IcdCodeDetails(
                remarks: mySelectedAssessment!.remark,
                complexDiagnosis: complexDiagnosis,
                conditionId: mySelectedAssessment!.selectedDiagnosisCondition!.id,
                diagnosisTypeId: mySelectedAssessment.selectedDiagnosisType!.id,
                icdcode10Id: mySelectedAssessment.selectedICD!.code)
          ]);
      await model?.postAssessment(postAssessmentRequestModel);
    }
    GifLoaderDialogUtils.hideDialog(context);
    if (model!.state == ViewState.ErrorLocal) {
      Utils.showErrorToast(model.error);
    } else {
      Map<String, dynamic> profile = await sharedPref.getObj(DOCTOR_PROFILE);

      DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
      mySelectedAssessment.icdCode10ID = mySelectedAssessment.selectedICD!.code;
      mySelectedAssessment.doctorName = doctorProfile.doctorName;
      widget.addSelectedAssessment(mySelectedAssessment, isUpdate);
      Navigator.of(context).pop();
    }
  }
}
