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/model/admissionRequest/admission-request.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/patient-admission-request-viewmodel.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/screens/base/base_view.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/patients/patient_service_title.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/app_bar/patient-profile-app-bar.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/dailog-list-select.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:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

import '../../../../routes.dart';

class AdmissionRequestFirstScreen extends StatefulWidget {
  @override
  _AdmissionRequestThirdScreenState createState() => _AdmissionRequestThirdScreenState();
}

class _AdmissionRequestThirdScreenState extends State<AdmissionRequestFirstScreen> {
  final _dietTypeRemarksController = TextEditingController();
  final _sickLeaveCommentsController = TextEditingController();
  final _postMedicalHistoryController = TextEditingController();
  final _postSurgicalHistoryController = TextEditingController();

  dynamic _selectedClinic;
  dynamic _selectedDoctor;
  dynamic _selectedDietType;

  bool _isSickLeaveRequired = false;
  bool _patientPregnant = false;

  String? clinicError = '';
  String? doctorError = '';
  String? sickLeaveCommentError = '';
  String? dietTypeError = '';
  String? medicalHistoryError = '';
  String? surgicalHistoryError = '';
  String? dietTypeRemarksError = '';
  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    String patientType = routeArgs['patientType'];
    String arrivalType = routeArgs['arrivalType'];
    final screenSize = MediaQuery.of(context).size;
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<AdmissionRequestViewModel>(
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isShowAppBar: true,
        appBar: PatientProfileAppBar(patient),
        appBarTitle: TranslationBase.of(context).admissionRequest,
        body: GestureDetector(
          onTap: () {
            FocusScopeNode currentFocus = FocusScope.of(context);
            if (!currentFocus.hasPrimaryFocus) {
              currentFocus.unfocus();
            }
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 15,
                      ),
                      ServiceTitle(
                        title: "${TranslationBase.of(context).admission}",
                        subTitle: TranslationBase.of(context).request,
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 0, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child: AppText(
                                Utils.convertToTitleCase(TranslationBase.of(context).specialityAndDoctorDetail),
                                color: Color(0xFF2E303A),
                                fontSize: SizeConfig.textMultiplier! * 1.8,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).clinic,
                              isTextFieldHasSuffix: true,
                              validationError: clinicError,
                              dropDownText: _selectedClinic != null
                                  ? projectViewModel.isArabic
                                      ? _selectedClinic['clinicNameArabic']
                                      : _selectedClinic['clinicNameEnglish']
                                  : null,
                              enabled: false,
                              onClick: model.clinicList != null && model.clinicList.length > 0
                                  ? () {
                                      openListDialogField(projectViewModel.isArabic ? 'clinicNameArabic' : 'clinicNameEnglish', 'clinicID', model.clinicList, (selectedValue) {
                                        setState(() {
                                          _selectedClinic = selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(context);
                                      await model.getClinics().then((_) => GifLoaderDialogUtils.hideDialog(context));
                                      if (model.state == ViewState.Idle && model.clinicList.length > 0) {
                                        openListDialogField(projectViewModel.isArabic ? 'clinicNameArabic' : 'clinicNameEnglish', 'clinicID', model.clinicList, (selectedValue) {
                                          setState(() {
                                            _selectedClinic = selectedValue;
                                          });
                                        });
                                      } else if (model.state == ViewState.ErrorLocal) {
                                        DrAppToastMsg.showErrorToast(model.error);
                                      } else {
                                        DrAppToastMsg.showErrorToast("Empty List");
                                      }
                                    },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).doctor,
                              isTextFieldHasSuffix: true,
                              dropDownText: _selectedDoctor != null ? _selectedDoctor['DoctorName'] : null,
                              enabled: false,
                              validationError: doctorError,
                              onClick: _selectedClinic != null
                                  ? model.doctorsList != null && model.doctorsList.length > 0
                                      ? () {
                                          openListDialogField('DoctorName', 'DoctorID', model.doctorsList, (selectedValue) {
                                            setState(() {
                                              _selectedDoctor = selectedValue;
                                            });
                                          });
                                        }
                                      : () async {
                                          GifLoaderDialogUtils.showMyDialog(context);
                                          await model.getClinicDoctors(_selectedClinic['clinicID']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                          if (model.state == ViewState.Idle && model.doctorsList.length > 0) {
                                            openListDialogField('DoctorName', 'DoctorID', model.doctorsList, (selectedValue) {
                                              setState(() {
                                                _selectedDoctor = selectedValue;
                                              });
                                            });
                                          } else if (model.state == ViewState.ErrorLocal) {
                                            DrAppToastMsg.showErrorToast(model.error);
                                          } else {
                                            DrAppToastMsg.showErrorToast("Empty List");
                                          }
                                        }
                                  : null,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 16,
                            ),
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child: AppText(
                                TranslationBase.of(context).patientDetails,
                                fontFamily: 'Poppins',
                                fontSize: SizeConfig.textMultiplier! * 1.8,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                            if (patient.gender != 1)
                              CheckboxListTile(
                                title: AppText(
                                  TranslationBase.of(context).patientPregnant,
                                  fontWeight: FontWeight.normal,
                                  fontFamily: 'Poppins',
                                  fontSize: SizeConfig.textMultiplier! * 2.0,
                                ),
                                value: _patientPregnant,
                                activeColor: HexColor("#D02127"),
                                onChanged: (newValue) {
                                  setState(() {
                                    _patientPregnant = newValue!;
                                  });
                                },
                                controlAffinity: ListTileControlAffinity.leading,
                                contentPadding: EdgeInsets.all(0),
                              ),
                            CheckboxListTile(
                              title: AppText(
                                TranslationBase.of(context).isSickLeaveRequired,
                                fontWeight: FontWeight.normal,
                                fontFamily: 'Poppins',
                                fontSize: SizeConfig.textMultiplier! * 2.0,
                              ),
                              value: _isSickLeaveRequired,
                              activeColor: HexColor("#D02127"),
                              onChanged: (newValue) {
                                setState(() {
                                  _isSickLeaveRequired = newValue!;
                                });
                              },
                              controlAffinity: ListTileControlAffinity.leading,
                              contentPadding: EdgeInsets.all(0),
                            ),
                            SizedBox(
                              height: 8,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).sickLeaveComments,
                              controller: _sickLeaveCommentsController,
                              minLines: 2,
                              maxLines: 4,
                              validationError: sickLeaveCommentError,
                              inputType: TextInputType.multiline,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).dietType,
                              isTextFieldHasSuffix: true,
                              validationError: dietTypeError,
                              dropDownText: _selectedDietType != null ? _selectedDietType['nameEn'] : null,
                              enabled: false,
                              onClick: model.dietTypesList != null && model.dietTypesList.length > 0
                                  ? () {
                                      openListDialogField('nameEn', 'id', model.dietTypesList, (selectedValue) {
                                        setState(() {
                                          _selectedDietType = selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(context);
                                      await model.getDietTypes(patient.patientId).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                      if (model.state == ViewState.Idle && model.dietTypesList.length > 0) {
                                        openListDialogField('nameEn', 'id', model.dietTypesList, (selectedValue) {
                                          setState(() {
                                            _selectedDietType = selectedValue;
                                          });
                                        });
                                      } else if (model.state == ViewState.ErrorLocal) {
                                        DrAppToastMsg.showErrorToast(model.error);
                                      } else {
                                        DrAppToastMsg.showErrorToast("Empty List");
                                      }
                                    },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).dietTypeRemarks,
                              controller: _dietTypeRemarksController,
                              minLines: 4,
                              maxLines: 6,
                              validationError:dietTypeRemarksError ,
                              inputType: TextInputType.multiline,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).pastMedicalHistory,
                              controller: _postMedicalHistoryController,
                              minLines: 4,
                              maxLines: 6,
                              validationError: medicalHistoryError,
                              inputType: TextInputType.multiline,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).pastSurgicalHistory,
                              controller: _postSurgicalHistoryController,
                              minLines: 2,
                              maxLines: 4,
                              validationError: surgicalHistoryError,
                              inputType: TextInputType.multiline,
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 100,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        bottomSheet: CustomBottomSheetContainer(
          label: "${TranslationBase.of(context).next}",
          onTap: () async {
            await locator<AnalyticsService>().logEvent(
              eventCategory: "Admission Request First Screen",
              eventAction: "Go To Admission Request Two",
            );
            model.admissionRequestData = AdmissionRequest();
            if (_selectedClinic != null &&
                _selectedDoctor != null &&
                _sickLeaveCommentsController.text != "" &&
                _postMedicalHistoryController.text != "" &&
                _postSurgicalHistoryController.text != "") {
              model.admissionRequestData.patientMRN = patient.patientMRN;
              model.admissionRequestData.appointmentNo = patient.appointmentNo;
              model.admissionRequestData.episodeID = patient.episodeNo;
              model.admissionRequestData.admissionRequestNo = 0;

              model.admissionRequestData.admitToClinic = _selectedClinic['clinicID'];
              model.admissionRequestData.mrpDoctorID = _selectedDoctor['DoctorID'];

              model.admissionRequestData.isPregnant = _patientPregnant;
              model.admissionRequestData.isSickLeaveRequired = _isSickLeaveRequired;
              model.admissionRequestData.sickLeaveComments = _sickLeaveCommentsController.text;
              model.admissionRequestData.isDietType = _selectedDietType != null ? true : false;
              model.admissionRequestData.dietType = _selectedDietType != null ? _selectedDietType['id'] : 0;
              model.admissionRequestData.dietRemarks = _dietTypeRemarksController.text;
              model.admissionRequestData.diagnosis = "0";
              model.admissionRequestData.pastMedicalHistory = _postMedicalHistoryController.text;
              model.admissionRequestData.pastSurgicalHistory = _postSurgicalHistoryController.text;
              Navigator.of(context)
                  .pushNamed(PATIENT_ADMISSION_REQUEST_2, arguments: {'patient': patient, 'patientType': patientType, 'arrivalType': arrivalType, 'admission-data': model.admissionRequestData});
            } else {
              DrAppToastMsg.showErrorToast(TranslationBase.of(context).pleaseFill);

              setState(() {
                if (_selectedClinic == null) {
                  clinicError = TranslationBase.of(context).fieldRequired;
                } else {
                  clinicError = null;
                }
                if (_selectedDoctor == null) {
                  doctorError = TranslationBase.of(context).fieldRequired;
                } else {
                  doctorError = null;
                }
                if (_sickLeaveCommentsController.text == "") {
                  sickLeaveCommentError = TranslationBase.of(context).fieldRequired;
                } else {
                  sickLeaveCommentError = null;
                }
                if (_selectedDietType == null) {
                  dietTypeError = TranslationBase.of(context).fieldRequired;
                } else {
                  dietTypeError = null;
                }
                if (_postMedicalHistoryController.text == "") {
                  medicalHistoryError = TranslationBase.of(context).fieldRequired;
                } else {
                  medicalHistoryError = null;
                }
                if (_postSurgicalHistoryController.text == "") {
                  surgicalHistoryError = TranslationBase.of(context).fieldRequired;
                } else {
                  surgicalHistoryError = null;
                }
                if (_dietTypeRemarksController.text == "") {
                  dietTypeRemarksError = TranslationBase.of(context).fieldRequired;
                } else {
                  dietTypeRemarksError = null;
                }

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

  void openListDialogField(String attributeName, String attributeValueId, List<dynamic> list, Function(dynamic selectedValue) okFunction) {
    ListSelectDialog dialog = ListSelectDialog(
      list: list,
      attributeName: attributeName,
      attributeValueId: attributeValueId,
      usingSearch: true,
      okText: TranslationBase.of(context).ok,
      okFunction: (selectedValue) {
        okFunction(selectedValue);
      },
    );
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return dialog;
      },
    );
  }
}
