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/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/widgets/bottom_sheet/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/buttons/app_buttons_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 AdmissionRequestThirdScreen extends StatefulWidget {
  @override
  _AdmissionRequestThirdScreenState createState() => _AdmissionRequestThirdScreenState();
}

class _AdmissionRequestThirdScreenState extends State<AdmissionRequestThirdScreen> {
  dynamic _selectedDiagnosis;
  dynamic _selectedIcd;
  dynamic _selectedDiagnosisType;

  String diagnosisError = '', icdError = '', diagnosisTypeError = '';

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    AdmissionRequest admissionRequest = routeArgs['admission-data'];

    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(
            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: [
                          AppText(
                            TranslationBase.of(context).diagnosisDetail,
                            color: Color(0xFF2E303A),
                            fontSize: SizeConfig.textMultiplier! * 1.8,
                            fontWeight: FontWeight.w700,
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFieldCustom(
                            height: screenSize.height * 0.075,
                            hintText: TranslationBase.of(context).diagnosis,
                            dropDownText: _selectedDiagnosis != null ? _selectedDiagnosis['nameEn'] : null,
                            enabled: false,
                            isTextFieldHasSuffix: true,
                            validationError: diagnosisError,
                            onClick: model.diagnosisTypesList != null && model.diagnosisTypesList.length > 0
                                ? () {
                                    openListDialogField('nameEn', 'id', model.diagnosisTypesList, (selectedValue) {
                                      setState(() {
                                        _selectedDiagnosis = selectedValue;
                                      });
                                    });
                                  }
                                : () async {
                                    GifLoaderDialogUtils.showMyDialog(context);
                                    await model.getDiagnosis().then((_) => GifLoaderDialogUtils.hideDialog(context));
                                    if (model.state == ViewState.Idle && model.diagnosisTypesList.length > 0) {
                                      openListDialogField('nameEn', 'id', model.diagnosisTypesList, (selectedValue) {
                                        setState(() {
                                          _selectedDiagnosis = selectedValue;
                                        });
                                      });
                                    } else if (model.state == ViewState.ErrorLocal) {
                                      DrAppToastMsg.showErrorToast(model.error);
                                    } else {
                                      DrAppToastMsg.showErrorToast("Empty List");
                                    }
                                  },
                            onChanged: (value) {},
                            onFieldSubmitted: () {},
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFieldCustom(
                            height: screenSize.height * 0.075,
                            hintText: TranslationBase.of(context).icd,
                            dropDownText: _selectedIcd != null ? _selectedIcd['description'] : null,
                            enabled: false,
                            isTextFieldHasSuffix: true,
                            validationError: icdError,
                            onClick: model.icdCodes != null && model.icdCodes.length > 0
                                ? () {
                                    openListDialogField('description', 'code', model.icdCodes, (selectedValue) {
                                      setState(() {
                                        _selectedIcd = selectedValue;
                                      });
                                    });
                                  }
                                : () async {
                                    GifLoaderDialogUtils.showMyDialog(context);
                                    await model.getICDCodes(patient.patientMRN!).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                    if (model.state == ViewState.Idle && model.icdCodes.length > 0) {
                                      openListDialogField('description', 'code', model.icdCodes, (selectedValue) {
                                        setState(() {
                                          _selectedIcd = selectedValue;
                                        });
                                      });
                                    } else if (model.state == ViewState.ErrorLocal) {
                                      DrAppToastMsg.showErrorToast(model.error);
                                    } else {
                                      DrAppToastMsg.showErrorToast("Empty List");
                                    }
                                  },
                            onChanged: (value) {},
                            onFieldSubmitted: () {},
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          AppTextFieldCustom(
                            height: screenSize.height * 0.075,
                            hintText: TranslationBase.of(context).diagnoseType,
                            dropDownText: _selectedDiagnosisType != null ? _selectedDiagnosisType['description'] : null,
                            enabled: false,
                            isTextFieldHasSuffix: true,
                            validationError: diagnosisTypeError,
                            onClick: model.listOfDiagnosisSelectionTypes != null && model.listOfDiagnosisSelectionTypes.length > 0
                                ? () {
                                    openListDialogField('description', 'code', model.listOfDiagnosisSelectionTypes, (selectedValue) {
                                      setState(() {
                                        _selectedDiagnosisType = selectedValue;
                                      });
                                    });
                                  }
                                : () async {
                                    GifLoaderDialogUtils.showMyDialog(context);
                                    await model.getMasterLookup(MasterKeysService.DiagnosisSelectionType).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                    if (model.state == ViewState.Idle && model.listOfDiagnosisSelectionTypes.length > 0) {
                                      openListDialogField('description', 'code', model.listOfDiagnosisSelectionTypes, (selectedValue) {
                                        setState(() {
                                          _selectedDiagnosisType = selectedValue;
                                        });
                                      });
                                    } else if (model.state == ViewState.ErrorLocal) {
                                      DrAppToastMsg.showErrorToast(model.error);
                                    } else {
                                      DrAppToastMsg.showErrorToast("Empty List");
                                    }
                                  },
                            onChanged: (value) {},
                            onFieldSubmitted: () {},
                          ),
                          SizedBox(
                            height: 10,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Row(
                  children: [
                    Expanded(
                      child: AppButton(
                        title: TranslationBase.of(context).previous,
                        color: HexColor("#EAEAEA"),
                        fontColor: Colors.black,
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                      child: AppButton(
                        title: TranslationBase.of(context).submit,
                        color: HexColor("#359846"),
                        onPressed: () async {
                          await locator<AnalyticsService>().logEvent(
                            eventCategory: "Admission Request Third Screen",
                            eventAction: "Submit Admission Request",
                          );
                          if (_selectedDiagnosis != null && _selectedIcd != null && _selectedDiagnosisType != null) {
                            model.admissionRequestData = admissionRequest;

                            dynamic admissionRequestDiagnoses = [
                              {
                                'diagnosisDescription': _selectedDiagnosis['nameEn'],
                                'diagnosisType': _selectedDiagnosis['id'],
                                'icdCode': _selectedIcd['code'],
                                'icdCodeDescription': _selectedIcd['description'],
                                'type': _selectedDiagnosisType['code'],
                                'remarks': "",
                                'isActive': true,
                              }
                            ];
                            model.admissionRequestData!.admissionRequestDiagnoses = admissionRequestDiagnoses;

                            await model.makeAdmissionRequest();
                            if (model.state == ViewState.ErrorLocal) {
                              DrAppToastMsg.showErrorToast(model.error);
                            } else {
                              DrAppToastMsg.showSuccesToast(TranslationBase.of(context).admissionRequestSuccessMsg);
                              Navigator.popUntil(context, ModalRoute.withName(PATIENTS_PROFILE));
                            }
                          } else {
                            DrAppToastMsg.showErrorToast(TranslationBase.of(context).pleaseFill);

                            setState(() {
                              if (_selectedDiagnosis == null) {
                                diagnosisError = TranslationBase.of(context).fieldRequired;
                              } else {
                                diagnosisError = "";
                              }

                              if (_selectedIcd == null) {
                                icdError = TranslationBase.of(context).fieldRequired;
                              } else {
                                icdError = "";
                              }

                              if (_selectedDiagnosisType == null) {
                                diagnosisTypeError = TranslationBase.of(context).fieldRequired;
                              } else {
                                diagnosisTypeError = "";
                              }
                            });
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        bottomSheet: BottomSheetContainer(
            widget: Row(
          children: [
            Container(
              width: MediaQuery.of(context).size.width * 0.4,
              child: AppButton(
                title: TranslationBase.of(context).previous,
                color: HexColor("#EAEAEA"),
                fontColor: Colors.black,
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Container(
              width: MediaQuery.of(context).size.width * 0.4,
              child: AppButton(
                title: TranslationBase.of(context).submit,
                color: HexColor("#359846"),
                onPressed: () async {
                  await locator<AnalyticsService>().logEvent(
                    eventCategory: "Admission Request Third Screen",
                    eventAction: "Submit Admission Request",
                  );
                  if (_selectedDiagnosis != null && _selectedIcd != null && _selectedDiagnosisType != null) {
                    model.admissionRequestData = admissionRequest;

                    dynamic admissionRequestDiagnoses = [
                      {
                        'diagnosisDescription': _selectedDiagnosis['nameEn'],
                        'diagnosisType': _selectedDiagnosis['id'],
                        'icdCode': _selectedIcd['code'],
                        'icdCodeDescription': _selectedIcd['description'],
                        'type': _selectedDiagnosisType['code'],
                        'remarks': "",
                        'isActive': true,
                      }
                    ];
                    model.admissionRequestData!.admissionRequestDiagnoses = admissionRequestDiagnoses;

                    await model.makeAdmissionRequest();
                    if (model.state == ViewState.ErrorLocal) {
                      DrAppToastMsg.showErrorToast(model.error);
                    } else {
                      DrAppToastMsg.showSuccesToast(TranslationBase.of(context).admissionRequestSuccessMsg);
                      Navigator.popUntil(context, ModalRoute.withName(PATIENTS_PROFILE));
                    }
                  } else {
                    DrAppToastMsg.showErrorToast(TranslationBase.of(context).pleaseFill);

                    setState(() {
                      if (_selectedDiagnosis == null) {
                        diagnosisError = TranslationBase.of(context).fieldRequired;
                      } else {
                        diagnosisError = "";
                      }

                      if (_selectedIcd == null) {
                        icdError = TranslationBase.of(context).fieldRequired;
                      } else {
                        icdError = "";
                      }

                      if (_selectedDiagnosisType == null) {
                        diagnosisTypeError = TranslationBase.of(context).fieldRequired;
                      } else {
                        diagnosisTypeError = "";
                      }
                    });
                  }
                },
              ),
            ),
          ],
        )),
      ),
    );
  }

  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;
      },
    );
  }
}
