import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
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/auth_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/PatchAssessmentReqModel.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/SOAP/post_assessment_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/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/dialogs/master_key_dailog.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/auto_complete_text_field.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/text_fields_utils.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.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,
      this.mySelectedAssessment,
      this.addSelectedAssessment,
      this.patientInfo,
      this.isUpdate = false,
      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;

  @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 {
          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);
          }
        },
        builder: (_, model, w) => AppScaffold(
          baseViewModel: model,
          isShowAppBar: false,
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body: SingleChildScrollView(
            child: Center(
              child: Column(
                children: [
                  BottomSheetTitle(
                      title: TranslationBase.of(context).addAssessmentDetails),
                  FractionallySizedBox(
                    widthFactor: 0.9,
                    child: Container(
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                          SizedBox(
                            height: 16,
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 0, right: 0, top: 15),
                            child: AppTextFieldCustom(
                              // height: 55.0,
                              hintText:
                                  TranslationBase.of(context).appointmentNumber,
                              isTextFieldHasSuffix: false,
                              enabled: false,
                              controller: appointmentIdController,
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            child: InkWell(
                                onTap: model.listOfICD10 != null
                                    ? () {
                                        setState(() {
                                          widget.mySelectedAssessment
                                              .selectedICD = null;
                                          icdNameController.text = null;
                                        });
                                      }
                                    : null,
                                child: widget
                                            .mySelectedAssessment.selectedICD ==
                                        null
                                    ? CustomAutoCompleteTextField(
                                        isShowError: isFormSubmitted &&
                                            widget.mySelectedAssessment
                                                    .selectedICD ==
                                                null,
                                        child: AutoCompleteTextField<
                                            MasterKeyModel>(
                                          decoration: TextFieldsUtils
                                              .textFieldSelectorDecoration(
                                                  TranslationBase.of(context)
                                                      .nameOrICD,
                                                  null,
                                                  true,
                                                  suffixIcon: Icons.search),
                                          itemSubmitted: (item) => setState(() {
                                            widget.mySelectedAssessment
                                                .selectedICD = item;
                                            icdNameController.text =
                                                '${item.code.trim()}/${item.description}';
                                          }),
                                          key: key,
                                          suggestions: model.listOfICD10,
                                          itemBuilder: (context, suggestion) =>
                                              new Padding(
                                                  child: AppText(
                                                      suggestion.description +
                                                          " / " +
                                                          suggestion.code
                                                              .toString()),
                                                  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()),
                                        ),
                                      )
                                    : AppTextFieldCustom(
                                        onClick: model.listOfICD10 != null
                                            ? () {
                                                setState(() {
                                                  widget.mySelectedAssessment
                                                      .selectedICD = null;
                                                  icdNameController.text = null;
                                                });
                                              }
                                            : null,
                                        hintText: TranslationBase.of(context)
                                            .nameOrICD,
                                        maxLines: 2,
                                        minLines: 1,
                                        controller: icdNameController,
                                        enabled: true,
                                        isTextFieldHasSuffix: true,
                                        suffixIcon: IconButton(
                                            icon: Icon(
                                          Icons.search,
                                          color: Colors.grey.shade600,
                                        )),
                                      )),
                          ),
                          SizedBox(
                            height: 7,
                          ),
                          AppTextFieldCustom(
                            onClick: model.listOfDiagnosisCondition != null
                                ? () {
                                    MasterKeyDailog dialog = MasterKeyDailog(
                                      list: model.listOfDiagnosisCondition,
                                      okText: TranslationBase.of(context).ok,
                                      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: 2,
                            minLines: 1,
                            controller: conditionController,
                            isTextFieldHasSuffix: true,
                            enabled: false,
                            hasBorder: true,
                            validationError: isFormSubmitted &&
                                    widget.mySelectedAssessment
                                            .selectedDiagnosisCondition ==
                                        null
                                ? TranslationBase.of(context).emptyMessage
                                : null,
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFieldCustom(
                            onClick: model.listOfDiagnosisType != null
                                ? () {
                                    MasterKeyDailog dialog = MasterKeyDailog(
                                      list: model.listOfDiagnosisType,
                                      okText: TranslationBase.of(context).ok,
                                      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: 2,
                            minLines: 1,
                            enabled: false,
                            isTextFieldHasSuffix: true,
                            controller: typeController,
                            hasBorder: true,
                            validationError: isFormSubmitted &&
                                    widget.mySelectedAssessment
                                            .selectedDiagnosisType ==
                                        null
                                ? TranslationBase.of(context).emptyMessage
                                : null,
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 0, right: 0, top: 15),
                            child: AppTextFieldCustom(
                              hintText: TranslationBase.of(context).remarks,
                              maxLines: 18,
                              minLines: 5,
                              controller: remarkController,
                              onChanged: (value) {
                                widget.mySelectedAssessment.remark =
                                    remarkController.text;
                              },
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                        ])),
                  ),
                ],
              ),
            ),
          ),
          bottomSheet: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(
                Radius.circular(0.0),
              ),
              border: Border.all(color: HexColor('#707070'), width: 0),
            ),
            height: MediaQuery.of(context).size.height * 0.1,
            width: double.infinity,
            child: Column(
              children: [
                SizedBox(
                  height: 10,
                ),
                Container(
                  child: FractionallySizedBox(
                    widthFactor: .80,
                    child: Center(
                      child: AppButton(
                        fontWeight: FontWeight.w700,
                        color: Colors.green,
                        title: (widget.isUpdate
                            ? 'Update Assessment Details'
                            : 'Add Assessment Details'),
                        loading: model.state == ViewState.BusyLocal,
                        onPressed: () 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);
                          }
                        },
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  submitAssessment(
      {SOAPViewModel model,
      MySelectedAssessment mySelectedAssessment,
      bool isUpdate = false}) async {
    if (isUpdate) {
      PatchAssessmentReqModel patchAssessmentReqModel = PatchAssessmentReqModel(
          patientMRN: widget.patientInfo.patientMRN,
          episodeID: widget.patientInfo.episodeNo,
          appointmentNo: widget.patientInfo.appointmentNo,
          remarks: mySelectedAssessment.remark,
          complexDiagnosis: true,
          conditionId: mySelectedAssessment.selectedDiagnosisCondition.id,
          diagnosisTypeId: mySelectedAssessment.selectedDiagnosisType.id,
          icdcode10Id: mySelectedAssessment.selectedICD.code,
          prevIcdCode10ID: mySelectedAssessment.icdCode10ID);

      await model.patchAssessment(patchAssessmentReqModel);
    } else {
      PostAssessmentRequestModel postAssessmentRequestModel =
          new PostAssessmentRequestModel(
              patientMRN: widget.patientInfo.patientMRN,
              episodeId: widget.patientInfo.episodeNo,
              appointmentNo: widget.patientInfo.appointmentNo,
              icdCodeDetails: [
            new IcdCodeDetails(
                remarks: mySelectedAssessment.remark,
                complexDiagnosis: true,
                conditionId: mySelectedAssessment.selectedDiagnosisCondition.id,
                diagnosisTypeId: mySelectedAssessment.selectedDiagnosisType.id,
                icdcode10Id: mySelectedAssessment.selectedICD.code)
          ]);

      await model.postAssessment(postAssessmentRequestModel);
    }

    if (model.state == ViewState.ErrorLocal) {
      Helpers.showErrorToast(model.error);
    } else {
      Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

      DoctorProfileModel doctorProfile = DoctorProfileModel.fromJson(profile);
      mySelectedAssessment.icdCode10ID = mySelectedAssessment.selectedICD.code;
      mySelectedAssessment.doctorName = doctorProfile.doctorName;

      if (!isUpdate) {
        widget.addSelectedAssessment(mySelectedAssessment, isUpdate);
      }
      Navigator.of(context).pop();
    }
  }
}
