import 'package:doctor_app_flutter/config/config.dart';
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/viewstate.dart';
import 'package:doctor_app_flutter/core/model/admissionRequest/admission-request.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/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/date-utils.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.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/patients/profile/patient-page-header-widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.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:flutter/material.dart';
import 'package:flutter/services.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> {
  final _treatmentLineController = TextEditingController();
  final _complicationsController = TextEditingController();
  final _otherProceduresController = TextEditingController();

  dynamic _selectedAdmissionType;
  dynamic _selectedDiagnosis;
  dynamic _selectedIcd;
  dynamic _selectedDiagnosisType;

  @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,
        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: [
                    PatientPageHeaderWidget(patient),
                    Container(
                      margin:
                          EdgeInsets.symmetric(vertical: 16, horizontal: 16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                              child: TextField(
                            decoration: Helpers.textFieldSelectorDecoration(
                                TranslationBase.of(context).treatmentLine,
                                null,
                                false),
                            enabled: true,
                            controller: _treatmentLineController,
                            keyboardType: TextInputType.text,
                            minLines: 3,
                            maxLines: 5,
                          )),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                              child: TextField(
                            decoration: Helpers.textFieldSelectorDecoration(
                                TranslationBase.of(context).complications,
                                null,
                                false),
                            enabled: true,
                            controller: _complicationsController,
                            keyboardType: TextInputType.text,
                            minLines: 3,
                            maxLines: 5,
                          )),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                              child: TextField(
                            decoration: Helpers.textFieldSelectorDecoration(
                                TranslationBase.of(context).otherProcedure,
                                null,
                                false),
                            enabled: true,
                            controller: _otherProceduresController,
                            keyboardType: TextInputType.text,
                            minLines: 3,
                            maxLines: 5,
                          )),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            height: screenSize.height * 0.070,
                            child: InkWell(
                              onTap: model.admissionTypeList != null &&
                                      model.admissionTypeList.length > 0
                                  ? () {
                                      openListDialogField('nameEn', 'id',
                                          model.admissionTypeList,
                                          (selectedValue) {
                                        setState(() {
                                          _selectedAdmissionType =
                                              selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(
                                          context);
                                      await model
                                          .getMasterLookup(MasterKeysService
                                              .AdmissionRequestType)
                                          .then((_) =>
                                              GifLoaderDialogUtils.hideDialog(
                                                  context));
                                      if (model.state == ViewState.Idle &&
                                          model.admissionTypeList.length > 0) {
                                        openListDialogField('nameEn', 'id',
                                            model.admissionTypeList,
                                            (selectedValue) {
                                          setState(() {
                                            _selectedAdmissionType =
                                                selectedValue;
                                          });
                                        });
                                      } else if (model.state ==
                                          ViewState.ErrorLocal) {
                                        DrAppToastMsg.showErrorToast(
                                            model.error);
                                      } else {
                                        DrAppToastMsg.showErrorToast(
                                            "Empty List");
                                      }
                                    },
                              child: TextField(
                                decoration: Helpers.textFieldSelectorDecoration(
                                    TranslationBase.of(context).admissionType,
                                    _selectedAdmissionType != null
                                        ? _selectedAdmissionType['nameEn']
                                        : null,
                                    true),
                                enabled: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 16,
                          ),
                          AppText(
                            TranslationBase.of(context).diagnosisDetail,
                            fontWeight: FontWeight.bold,
                            fontSize: SizeConfig.textMultiplier * 2.5,
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            height: screenSize.height * 0.070,
                            child: InkWell(
                              onTap: 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");
                                      }
                                    },
                              child: TextField(
                                decoration: Helpers.textFieldSelectorDecoration(
                                    TranslationBase.of(context).diagnosis,
                                    _selectedDiagnosis != null
                                        ? _selectedDiagnosis['nameEn']
                                        : null,
                                    true),
                                enabled: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            height: screenSize.height * 0.070,
                            child: InkWell(
                              onTap: 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");
                                      }
                                    },
                              child: TextField(
                                decoration: Helpers.textFieldSelectorDecoration(
                                    TranslationBase.of(context).icd,
                                    _selectedIcd != null
                                        ? _selectedIcd['description']
                                        : null,
                                    true),
                                enabled: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            height: screenSize.height * 0.070,
                            child: InkWell(
                              onTap: 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");
                                      }
                                    },
                              child: TextField(
                                decoration: Helpers.textFieldSelectorDecoration(
                                    TranslationBase.of(context).diagnoseType,
                                    _selectedDiagnosisType != null
                                        ? _selectedDiagnosisType['description']
                                        : null,
                                    true),
                                enabled: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: AppButton(
                  title: TranslationBase.of(context).next,
                  color: HexColor("#B8382B"),
                  onPressed: () async {
                    if (_treatmentLineController.text != "" &&
                        _complicationsController.text != "" &&
                        _otherProceduresController.text != "" &&
                        _selectedAdmissionType != null &&
                        _selectedDiagnosis != null &&
                        _selectedIcd != null &&
                        _selectedDiagnosisType != null) {
                      model.admissionRequestData = admissionRequest;

                      model.admissionRequestData.mainLineOfTreatment =
                          _treatmentLineController.text;
                      model.admissionRequestData.complications =
                          _complicationsController.text;
                      model.admissionRequestData.otherProcedures =
                          _otherProceduresController.text;
                      model.admissionRequestData.admissionType =
                          _selectedAdmissionType['id'];

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

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