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/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/date-utils.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/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:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

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

class AdmissionRequestSecondScreen extends StatefulWidget {
  @override
  _AdmissionRequestSecondScreenState createState() => _AdmissionRequestSecondScreenState();
}

class _AdmissionRequestSecondScreenState extends State<AdmissionRequestSecondScreen> {
  final _postPlansEstimatedCostController = TextEditingController();
  final _estimatedCostController = TextEditingController();
  final _expectedDaysController = TextEditingController();
  final _intendedLengthDaysController = TextEditingController();
  final _otherDepartmentsInterventionsController = TextEditingController();
  final _treatmentLineController = TextEditingController();
  final _complicationsController = TextEditingController();
  final _otherProceduresController = TextEditingController();

  DateTime? _expectedAdmissionDate;

  dynamic _selectedFloor;
  dynamic _selectedWard;
  dynamic _selectedRoomCategory;
  dynamic _selectedAdmissionType;

  String costError = '',
      plansError = '',
      otherInterventionsError = '',
      expectedDaysError = '',
      intendedDaysError = '',
      expectedDatesError = '',
      floorError = '',
      roomError = '',
      treatmentsError = '',
      complicationsError = '',
      proceduresError = '',
      admissionTypeError = '';

  @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'];
    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(
                              Utils.convertToTitleCase(
                                TranslationBase.of(context).postPlansEstimatedCost,
                              ),
                              color: Color(0xFF2E303A),
                              fontSize: SizeConfig.textMultiplier! * 1.8,
                              fontWeight: FontWeight.w700,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).estimatedCost,
                              controller: _estimatedCostController,
                              validationError: costError,
                              inputType: TextInputType.number,
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(ONLY_NUMBERS))],
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).postPlans,
                              controller: _postPlansEstimatedCostController,
                              inputType: TextInputType.multiline,
                              validationError: plansError,
                              minLines: 4,
                              maxLines: 6,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).otherDepartmentsInterventions,
                              controller: _otherDepartmentsInterventionsController,
                              inputType: TextInputType.multiline,
                              validationError: otherInterventionsError,
                              minLines: 2,
                              maxLines: 4,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppText(
                              TranslationBase.of(context).otherInformation,
                              color: Color(0xFF2E303A),
                              fontSize: SizeConfig.textMultiplier! * 1.8,
                              fontWeight: FontWeight.w700,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).expectedDays,
                              controller: _expectedDaysController,
                              validationError: expectedDaysError,
                              inputType: TextInputType.number,
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(
                                  RegExp(ONLY_NUMBERS),
                                )
                              ],
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).intendedLengthStay,
                              controller: _intendedLengthDaysController,
                              validationError: intendedDaysError,
                              inputType: TextInputType.number,
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(
                                  RegExp(ONLY_NUMBERS),
                                )
                              ],
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).expectedAdmissionDate,
                              dropDownText: _expectedAdmissionDate != null ? "${AppDateUtils.convertStringToDateFormat(_expectedAdmissionDate.toString(), "yyyy-MM-dd")}" : "",
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: expectedDatesError,
                              suffixIcon: IconButton(
                                icon: Icon(
                                  Icons.calendar_today,
                                  color: Colors.black,
                                ),
                                onPressed: () {},
                              ),
                              onClick: () {
                                if (_expectedAdmissionDate == null) {
                                  _expectedAdmissionDate = DateTime.now();
                                }
                                _selectDate(context, _expectedAdmissionDate!, (picked) {
                                  setState(() {
                                    _expectedAdmissionDate = picked;
                                  });
                                });
                              },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).floor,
                              dropDownText: _selectedFloor != null ? _selectedFloor['description'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: floorError,
                              onClick: model.floorList != null && model.floorList.length > 0
                                  ? () {
                                      openListDialogField('description', 'floorID', model.floorList, (selectedValue) {
                                        setState(() {
                                          _selectedFloor = selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(context);
                                      await model.getFloors().then((_) => GifLoaderDialogUtils.hideDialog(context));
                                      if (model.state == ViewState.Idle && model.floorList.length > 0) {
                                        openListDialogField('description', 'floorID', model.floorList, (selectedValue) {
                                          setState(() {
                                            _selectedFloor = 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).ward,
                              dropDownText: _selectedWard != null ? _selectedWard['description'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              onClick: model.wardList != null && model.wardList.length > 0
                                  ? () {
                                      openListDialogField('description', 'nursingStationID', model.wardList, (selectedValue) {
                                        setState(() {
                                          _selectedWard = selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(context);
                                      await model.getWards().then((_) => GifLoaderDialogUtils.hideDialog(context));
                                      if (model.state == ViewState.Idle && model.wardList.length > 0) {
                                        openListDialogField('description', 'nursingStationID', model.wardList, (selectedValue) {
                                          setState(() {
                                            _selectedWard = 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).roomCategory,
                              dropDownText: _selectedRoomCategory != null ? _selectedRoomCategory['description'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: roomError,
                              onClick: model.roomCategoryList != null && model.roomCategoryList.length > 0
                                  ? () {
                                      openListDialogField('description', 'categoryID', model.roomCategoryList, (selectedValue) {
                                        setState(() {
                                          _selectedRoomCategory = selectedValue;
                                        });
                                      });
                                    }
                                  : () async {
                                      GifLoaderDialogUtils.showMyDialog(context);
                                      await model.getRoomCategories().then((_) => GifLoaderDialogUtils.hideDialog(context));
                                      if (model.state == ViewState.Idle && model.roomCategoryList.length > 0) {
                                        openListDialogField('description', 'categoryID', model.roomCategoryList, (selectedValue) {
                                          setState(() {
                                            _selectedRoomCategory = 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).treatmentLine,
                              controller: _treatmentLineController,
                              inputType: TextInputType.multiline,
                              validationError: treatmentsError,
                              minLines: 3,
                              maxLines: 5,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).complications,
                              controller: _complicationsController,
                              inputType: TextInputType.multiline,
                              validationError: complicationsError,
                              minLines: 3,
                              maxLines: 5,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              hintText: TranslationBase.of(context).otherProcedure,
                              controller: _otherProceduresController,
                              inputType: TextInputType.multiline,
                              validationError: proceduresError,
                              minLines: 3,
                              maxLines: 5,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).admissionType,
                              dropDownText: _selectedAdmissionType != null ? _selectedAdmissionType['nameEn'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: admissionTypeError,
                              onClick: 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");
                                      }
                                    },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 100,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        bottomSheet: BottomSheetContainer(
            widget: Row(
          children: [
            Container(
              width: MediaQuery.of(context).size.width * 0.4,
              child: AppButton(
                title: TranslationBase.of(context).previous,
                color: HexColor('#EFEFEF'),
                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).next,
                color: AppGlobal.appRedColor,
                fontColor: Colors.white,
                onPressed: () async {
                  await locator<AnalyticsService>().logEvent(
                    eventCategory: "Admission Request Second Screen",
                    eventAction: "Go To Admission Request Three",
                  );
                  if (_estimatedCostController.text != "" &&
                      _postPlansEstimatedCostController.text != "" &&
                      _expectedDaysController.text != "" &&
                      _intendedLengthDaysController.text != "" &&
                      _expectedAdmissionDate != null &&
                      _otherDepartmentsInterventionsController.text != "" &&
                      _selectedFloor != null &&
                      _selectedRoomCategory != null /*_selectedWard is not required*/ &&
                      _treatmentLineController.text != "" &&
                      _complicationsController.text != "" &&
                      _otherProceduresController.text != "" &&
                      _selectedAdmissionType != null) {
                    model.admissionRequestData = admissionRequest;

                    model.admissionRequestData!.estimatedCost = int.parse(_estimatedCostController.text);
                    model.admissionRequestData!.elementsForImprovement = _postPlansEstimatedCostController.text;

                    model.admissionRequestData!.expectedDays = int.parse(_expectedDaysController.text);
                    model.admissionRequestData.intendedLengthOfStayId = int.parse(_intendedLengthDaysController.text);

                    model.admissionRequestData!.admissionDate = _expectedAdmissionDate!.toIso8601String();
                    model.admissionRequestData!.expectedadmissionDate = _expectedAdmissionDate!.toIso8601String();

                    model.admissionRequestData.otherDepartmentinterventions = _otherDepartmentsInterventionsController.text;
                    model.admissionRequestData!.admissionLocationID = _selectedFloor['floorID'];
                    model.admissionRequestData!.wardID = _selectedWard != null ? _selectedWard['nursingStationID'] : 0;
                    model.admissionRequestData!.roomCategoryID = _selectedRoomCategory['categoryID'];

                    model.admissionRequestData!.admissionRequestProcedures = [];

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

                    Navigator.of(context)
                        .pushNamed(PATIENT_ADMISSION_REQUEST_3, arguments: {'patient': patient, 'patientType': patientType, 'arrivalType': arrivalType, 'admission-data': model.admissionRequestData});
                  } else {
                    DrAppToastMsg.showErrorToast(TranslationBase.of(context).pleaseFill);

                    setState(() {
                      if (_estimatedCostController.text == "") {
                        costError = TranslationBase.of(context).fieldRequired;
                      } else {
                        costError = "";
                      }

                      if (_postPlansEstimatedCostController.text == "") {
                        plansError = TranslationBase.of(context).fieldRequired;
                      } else {
                        plansError = "";
                      }

                      if (_expectedDaysController.text == "") {
                        expectedDaysError = TranslationBase.of(context).fieldRequired;
                      } else {
                        expectedDaysError = "";
                      }

                      if (_intendedLengthDaysController.text == "") {
                        intendedDaysError = TranslationBase
                            .of(context)
                            .fieldRequired;
                      }else{
                        intendedDaysError = "";
                      }

                      if (_expectedAdmissionDate == null) {
                        expectedDatesError = TranslationBase.of(context).fieldRequired;
                      } else {
                        expectedDatesError = "";
                      }

                      if (_otherDepartmentsInterventionsController.text == "") {
                        otherInterventionsError = TranslationBase.of(context).fieldRequired;
                      } else {
                        otherInterventionsError = "";
                      }

                      if (_selectedFloor == null) {
                        floorError = TranslationBase.of(context).fieldRequired;
                      } else {
                        floorError = "";
                      }

                      if (_selectedRoomCategory == null) {
                        roomError = TranslationBase.of(context).fieldRequired;
                      } else {
                        roomError = "";
                      }

                      if (_treatmentLineController.text == "") {
                        treatmentsError = TranslationBase.of(context).fieldRequired;
                      } else {
                        treatmentsError = "";
                      }

                      if (_complicationsController.text == "") {
                        complicationsError = TranslationBase.of(context).fieldRequired;
                      } else {
                        complicationsError = "";
                      }

                      if (_otherProceduresController.text == "") {
                        proceduresError = TranslationBase.of(context).fieldRequired;
                      } else {
                        proceduresError = "";
                      }

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

  Future _selectDate(BuildContext context, DateTime dateTime, Function(DateTime picked) updateDate) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: dateTime,
      firstDate: DateTime.now(),
      lastDate: DateTime(2040),
      initialEntryMode: DatePickerEntryMode.calendar,
    );
    if (picked != null && picked != dateTime) {
      updateDate(picked);
    }
  }

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