import 'package:doctor_app_flutter/config/config.dart';
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/diagnosis/GetDiagnosisForInPatientRequestModel.dart';
import 'package:doctor_app_flutter/core/model/diagnosis/GetDiagnosisForInPatientResponseModel.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/provider/robot_provider.dart';
import 'package:doctor_app_flutter/core/viewModel/patient-referral-viewmodel.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.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/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/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/speech-text-popup.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;

import '../../../../../client/base_app_client.dart' show sharedPref;
import '../../../../../config/shared_pref_kay.dart' show SLECTED_PATIENT_TYPE;

class PatientMakeInPatientReferralScreen extends StatefulWidget {
  @override
  _PatientMakeInPatientReferralScreenState createState() => _PatientMakeInPatientReferralScreenState();
}

class _PatientMakeInPatientReferralScreenState extends State<PatientMakeInPatientReferralScreen> {
  PatiantInformtion? patient;
  List<dynamic>? referToList;
  dynamic _referTo;
  dynamic? selectedDiagnosis;
  dynamic _selectedBranch;
  dynamic _selectedClinic;
  dynamic _selectedDoctor;
  dynamic _selectedFrequency;
  dynamic _selectedPriority;
  final _remarksController = TextEditingController();
  final _extController = TextEditingController();
  int _activePriority = 1;
  String? appointmentDate;
  String? branchError;
  String? diagnosisError;
  String? hospitalError;
  String? clinicError;
  String? doctorError;
  String? frequencyError;
  String? priorityError;
  String? remarkError;
  String? extError;
  stt.SpeechToText speech = stt.SpeechToText();
  var recognizedWord;
  var event = RobotProvider();

  var isVidaPlusProject = false;

  @override
  void initState() {
    requestPermissions();
    event.controller.stream.listen((p) {
      if (p['startPopUp'] == 'true') {
        if (this.mounted) {
          initSpeechState().then((value) => {onVoiceText()});
        }
      }
    });
    super.initState();
  }

  onVoiceText() async {
    new SpeechToText(context: context).showAlertDialog(context);
    var lang = TranslationBase.of(AppGlobal.CONTEX).locale.languageCode;
    bool available = await speech.initialize(onStatus: statusListener, onError: errorListener);
    if (available) {
      speech.listen(
        onResult: resultListener,
        listenMode: stt.ListenMode.confirmation,
        localeId: lang == 'en' ? 'en-US' : 'ar-SA',
      );
    } else {
      print("The user has denied the use of speech recognition.");
    }
  }

  void errorListener(SpeechRecognitionError error) {
    event.setValue({"searchText": 'null'});
    //SpeechToText.closeAlertDialog(context);
    print(error);
  }

  void statusListener(String status) {
    recognizedWord = status == 'listening' ? 'Listening...' : 'Sorry....';
  }

  void requestPermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.microphone,
    ].request();
  }

  void resultListener(result) {
    recognizedWord = result.recognizedWords;
    event.setValue({"searchText": recognizedWord});

    if (result.finalResult == true) {
      setState(() {
        SpeechToText.closeAlertDialog(context);
        speech.stop();
        _remarksController.text += recognizedWord + '\n';
      });
    } else {
      print(result.finalResult);
    }
  }

  Future<void> initSpeechState() async {
    bool hasSpeech = await speech.initialize(onError: errorListener, onStatus: statusListener);
    print(hasSpeech);
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    dynamic priority1 = {
      "ParameterCode": isVidaPlusProject ? 2 :1,
      "Description": TranslationBase.of(context).veryUrgent.toUpperCase(),
    };
    dynamic priority2 = {
      "ParameterCode": isVidaPlusProject? 1 :2,
      'Description': TranslationBase.of(context).urgent.toUpperCase(),
    };
    dynamic priority3 = {
      "ParameterCode": isVidaPlusProject? 3  :0,
      'Description': TranslationBase.of(context).routine.toUpperCase(),
    };

    List<Object> _priorityList = [];
    _priorityList.add(priority1);
    _priorityList.add(priority2);
    _priorityList.add(priority3);

    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    patient = routeArgs['patient'];
    bool isInpatient = routeArgs['isInpatient'];
    isVidaPlusProject = routeArgs['isVidaPlusProject'];
    referToList = [];
    dynamic sameBranch = {"id": 1, "name": TranslationBase.of(context).sameBranch};
    dynamic otherBranch = {"id": 2, "name": TranslationBase.of(context).otherBranch};
    referToList!.add(sameBranch);
    referToList!.add(otherBranch);

    final screenSize = MediaQuery.of(context).size;

    getDiagnosisForInPatient(BuildContext context, PatientReferralViewModel model,
        {bool isLocalBusy = false}) async {
      final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
      PatiantInformtion patient = routeArgs['patient'];
      // String type = await sharedPref.getString(SLECTED_PATIENT_TYPE);
      //
      // print(type);
      String type = await sharedPref.getString(SLECTED_PATIENT_TYPE) == '0' ? "2" : "1";

      print(type);
      GetDiagnosisForInPatientRequestModel getDiagnosisForInPatientRequestModel =
      GetDiagnosisForInPatientRequestModel(
        admissionNo: isVidaPlusProject? patient.admissionID : int.parse(patient.admissionNo!),
        patientTypeID: patient.patientType,
        patientID: patient.patientId,
      );
      model.getDiagnosisForInPatient(getDiagnosisForInPatientRequestModel,isVidaPlusProject,patient);
    }

    return BaseView<PatientReferralViewModel>(
      onModelReady: (model) {
        model.getReferralFrequencyList();
        getDiagnosisForInPatient(context, model);
      },
      builder: (_, model, w) => AppScaffold(
          baseViewModel: model,
          appBarTitle: TranslationBase.of(context).referPatient,
          isShowAppBar: true,
          appBar: PatientProfileAppBar(
            patient!,
            isInpatient: isInpatient,
          ),
          body: SingleChildScrollView(
            child: Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 10,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: ServiceTitle(
                          title: TranslationBase.of(context).refer,
                          subTitle: TranslationBase.of(context).patient,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 0, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).branch,
                              dropDownText: _referTo != null ? _referTo['name'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: branchError,
                              onClick: referToList != null
                                  ? () {
                                      ListSelectDialog dialog = ListSelectDialog(
                                        list: referToList!,
                                        attributeName: 'name',
                                        attributeValueId: 'id',
                                        okText: TranslationBase.of(context).ok,
                                        okFunction: (selectedValue) async {
                                          setState(() {
                                            _referTo = selectedValue;
                                            _selectedBranch = null;
                                            _selectedClinic = null;
                                            _selectedDoctor = null;
                                            if (_referTo['id'] == 1) {
                                            model.getDoctorBranch().then((value) async {
                                              _selectedBranch = value;
                                                GifLoaderDialogUtils.showMyDialog(context);
                                                await model.getClinics(_selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                                if (model.state == ViewState.ErrorLocal) {
                                                  DrAppToastMsg.showErrorToast(model.error);
                                                }
                                              }
                                            );} else {
                                               model.getBranches();
                                            }
                                          });
                                        },
                                      );
                                      showDialog(
                                        barrierDismissible: false,
                                        context: context,
                                        builder: (BuildContext context) {
                                          return dialog;
                                        },
                                      );
                                    }
                                  : () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).hospital,
                              dropDownText: _selectedBranch != null ? _selectedBranch['facilityName'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: hospitalError,
                              onClick: model.branchesList != null && model.branchesList!.length > 0 && _referTo != null && _referTo['id'] == 2
                                  ? () {
                                      ListSelectDialog dialog = ListSelectDialog(
                                        list: model.branchesList!,
                                        attributeName: 'facilityName',
                                        attributeValueId: 'facilityId',
                                        okText: TranslationBase.of(context).ok,
                                        okFunction: (selectedValue) async {
                                          _selectedBranch = selectedValue;
                                          _selectedClinic = null;
                                          _selectedDoctor = null;
                                          GifLoaderDialogUtils.showMyDialog(context);
                                          await model.getClinics(_selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                          if (model.state == ViewState.ErrorLocal) {
                                            DrAppToastMsg.showErrorToast(model.error);
                                          }
                                        },
                                      );
                                      showDialog(
                                        barrierDismissible: false,
                                        context: context,
                                        builder: (BuildContext context) {
                                          return dialog;
                                        },
                                      );
                                    }
                                  : () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).clinic,
                              dropDownText: _selectedClinic != null ? _selectedClinic['ClinicDescription'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: clinicError,
                              onClick: _selectedBranch != null && model.clinicsList != null && model.clinicsList!.length > 0
                                  ? () {
                                      ListSelectDialog dialog = ListSelectDialog(
                                        list: model.clinicsList!,
                                        attributeName: 'ClinicDescription',
                                        attributeValueId: 'ClinicID',
                                        usingSearch: true,
                                        hintSearchText: TranslationBase.of(context).clinicSearch,
                                        okText: TranslationBase.of(context).ok,
                                        okFunction: (selectedValue) async {
                                          _selectedDoctor = null;
                                          _selectedClinic = selectedValue;
                                          GifLoaderDialogUtils.showMyDialog(context);
                                          await model.getClinicDoctors(patient!, _selectedClinic['ClinicID'], _selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                                          if (model.state == ViewState.ErrorLocal) {
                                            DrAppToastMsg.showErrorToast(model.error);
                                          }
                                        },
                                      );
                                      showDialog(
                                        barrierDismissible: false,
                                        context: context,
                                        builder: (BuildContext context) {
                                          return dialog;
                                        },
                                      );
                                    }
                                  : () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).doctor,
                              dropDownText: _selectedDoctor != null ? _selectedDoctor['Name'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: doctorError,
                              onClick: _selectedClinic != null && model.doctorsList != null && model.doctorsList.length > 0
                                  ? () {
                                      ListSelectDialog dialog = ListSelectDialog(
                                        list: model.doctorsList,
                                        attributeName: 'Name',
                                        attributeValueId: 'DoctorID',
                                        usingSearch: true,
                                        hintSearchText: TranslationBase.of(context).doctorSearch,
                                        okText: TranslationBase.of(context).ok,
                                        okFunction: (selectedValue) {
                                          setState(() {
                                            _selectedDoctor = selectedValue;
                                          });
                                        },
                                      );
                                      showDialog(
                                        barrierDismissible: false,
                                        context: context,
                                        builder: (BuildContext context) {
                                          return dialog;
                                        },
                                      );
                                    }
                                  : () {
                                      if (_selectedClinic == null) {
                                        DrAppToastMsg.showErrorToast("You need to select a clinic first");
                                      } else if (model.doctorsList == null || model.doctorsList.length == 0) {
                                        DrAppToastMsg.showErrorToast("There is no doctors for this clinic");
                                      }
                                    },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).priority,
                              dropDownText: _selectedPriority != null ? _selectedPriority['Description'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: priorityError,
                              onClick: () {
                                ListSelectDialog dialog = ListSelectDialog(
                                  list: _priorityList,
                                  attributeName: 'Description',
                                  attributeValueId: 'Description',
                                  usingSearch: false,
                                  okText: TranslationBase.of(context).ok,
                                  okFunction: (selectedValue) {
                                    setState(() {
                                      _selectedPriority = selectedValue;
                                      _activePriority = selectedValue["ParameterCode"];
                                    });
                                  },
                                );
                                showDialog(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dialog;
                                  },
                                );
                              },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Padding(
                              padding: const EdgeInsets.all(4.0),
                              child: AppText(
                                "${TranslationBase.of(context).replayBefore}:  ${getPriority()}",
                                fontWeight: FontWeight.normal,
                                fontSize: SizeConfig.textMultiplier! * 1.9,
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: screenSize.height * 0.075,
                              hintText: TranslationBase.of(context).referralFrequency,
                              dropDownText: _selectedFrequency != null ? _selectedFrequency['Description'] : null,
                              enabled: false,
                              isTextFieldHasSuffix: true,
                              validationError: frequencyError,
                              onClick: () {
                                ListSelectDialog dialog = ListSelectDialog(
                                  list: model.referralFrequencyList,
                                  attributeName: 'Description',
                                  attributeValueId: 'ParameterCode',
                                  usingSearch: true,
                                  hintSearchText: TranslationBase.of(context).selectReferralFrequency,
                                  okText: TranslationBase.of(context).ok,
                                  okFunction: (selectedValue) {
                                    setState(() {
                                      _selectedFrequency = selectedValue;
                                    });
                                  },
                                );
                                showDialog(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dialog;
                                  },
                                );
                              },
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            Visibility(
                              visible: isVidaPlusProject,
                              child:
                            Column(
                              children: [
                                SizedBox(
                                  height: 10,
                                ),
                                AppTextFieldCustom(
                                  height: screenSize.height * 0.075,
                                  hintText: TranslationBase.of(context).diagnosis,
                                  dropDownText: selectedDiagnosis != null ? selectedDiagnosis['selectedDisease'] : null,
                                  enabled: false,
                                  isTextFieldHasSuffix: true,
                                  validationError: diagnosisError,
                                  onClick:  () {
                                    ListSelectDialog dialog = ListSelectDialog(
                                      list: model.diagnosisForInPatientList,
                                      attributeName: 'selectedDisease',
                                      attributeValueId: 'selectedIcdCode',
                                      okText: TranslationBase.of(context).ok,
                                      okFunction: (selectedValue) {
                                        setState(() {
                                          selectedDiagnosis = selectedValue;
                                        });
                                      },
                                    );
                                    showDialog(
                                      barrierDismissible: false,
                                      context: context,
                                      builder: (BuildContext context) {
                                        return dialog;
                                      },
                                    );
                                  },
                                  onChanged: (value) {},
                                  onFieldSubmitted: () {},
                                ),
                              ],
                            ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              validationError: extError,
                              hintText: TranslationBase.of(context).ext,
                              controller: _extController,
                              inputType: TextInputType.text,
                              onClick: () {},
                              onChanged: (value) {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Stack(
                              children: [
                                AppTextFieldCustom(
                                  validationError: remarkError,
                                  hintText: "Remarks",
                                  controller: _remarksController,
                                  inputType: TextInputType.multiline,
                                  minLines: 4,
                                  maxLines: 6,
                                  onClick: () {},
                                  onChanged: (value) {},
                                  onFieldSubmitted: () {},
                                ),
                                Positioned(
                                  top: 0,
                                  right: 15,
                                  child: IconButton(
                                    icon: Icon(
                                      DoctorApp.speechtotext,
                                      color: Colors.black,
                                      size: 35,
                                    ),
                                    onPressed: () {
                                      initSpeechState().then((value) => {onVoiceText()});
                                    },
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 100,
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                  Column(
                    children: [
                      _remarksController.text.isEmpty
                          ? SizedBox()
                          : Container(
                              margin: EdgeInsets.all(5),
                              child: AppButton(
                                title: TranslationBase.of(context).clearText,
                                onPressed: () {
                                  setState(() {
                                    _remarksController.text = '';
                                  });
                                },
                              )),
                      SizedBox(
                        height: 10,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          bottomSheet:
          // model.state != ViewState.Idle
          //     ? Container(
          //         height: 0,
          //       )
          //     :
          CustomBottomSheetContainer(
                  label: "${TranslationBase.of(context).refer}",
                  onTap: () async {
                    setState(() {
                      if (_referTo == null) {
                        branchError = TranslationBase.of(context).fieldRequired;
                      } else {
                        branchError = null;
                      }
                      if (_selectedBranch == null) {
                        hospitalError = TranslationBase.of(context).fieldRequired;
                      } else {
                        hospitalError = null;
                      }
                      if (_selectedClinic == null) {
                        clinicError = TranslationBase.of(context).fieldRequired;
                      } else {
                        clinicError = null;
                      }
                      if (_selectedDoctor == null) {
                        doctorError = TranslationBase.of(context).fieldRequired;
                      } else {
                        doctorError = null;
                      }
                      if (_selectedFrequency == null) {
                        frequencyError = TranslationBase.of(context).fieldRequired;
                      } else {
                        frequencyError = null;
                      }
                      if  ( isVidaPlusProject && selectedDiagnosis == null) {
                        diagnosisError = TranslationBase.of(context).fieldRequired;
                      } else {
                        diagnosisError = null;
                      }
                      if (_selectedPriority == null) {
                        priorityError = TranslationBase.of(context).fieldRequired;
                      } else {
                        priorityError = null;
                      }
                      if (_remarksController.text.isEmpty ) {
                        remarkError = TranslationBase.of(context).fieldRequired;
                      } else {
                        remarkError = null;
                      }
                      if (_extController.text.isEmpty ) {
                        extError = TranslationBase.of(context).fieldRequired;
                      } else {
                        extError = null;
                      }
                    });
                    if (_selectedFrequency == null ||
                        _selectedPriority == null ||
                        _selectedBranch == null ||
                        _selectedClinic == null ||
                        _selectedDoctor == null ||
                        ( isVidaPlusProject && selectedDiagnosis == null) ||
                        _remarksController.text.isEmpty ||
                        _extController.text.isEmpty) return;
                    {
                      GifLoaderDialogUtils.showMyDialog(context);
                      await model.makeInPatientReferral(
                          patient: patient,
                          projectID: _selectedBranch['facilityId'],
                          clinicID: _selectedClinic['ClinicID'],
                          doctorID: _selectedDoctor['DoctorID'],
                          frequencyCode: _selectedFrequency['ParameterCode'],
                          ext: _extController.text,
                          remarks: _remarksController.text,
                          priority: _activePriority,
                          referralDate: appointmentDate,
                          diagnosis: selectedDiagnosis,
                          isLocalBusy: true,
                        isVidaPlusProject
                      );
                      GifLoaderDialogUtils.hideDialog(context);
                      if (model.state == ViewState.ErrorLocal)
                        DrAppToastMsg.showErrorToast(model.error);
                      else {
                        DrAppToastMsg.showSuccesToast(TranslationBase.of(context).referralSuccessMsg);
                        Navigator.pop(context);
                      }
                    }
                  },
                )),
    );
  }

  String getPriority() {
    DateTime date = DateTime.now();
    switch (_activePriority) {
      case 0:
        date = date.add(new Duration(hours: 3));
        break;
      case 1:
        date = date.add(new Duration(hours: 6));
        break;
      case 2:
        date = date.add(new Duration(days: 1));
        break;
    }
    var format = DateFormat('yyyy/MM/dd HH:mm a');
    var localAppointmentDate = format.format(date);
    appointmentDate = localAppointmentDate;
    String time = AppDateUtils.getDayMonthYearDateFormatted(date) + ' ' + AppDateUtils.getHour(date);

    return time;
  }

  BoxDecoration containerBorderDecoration(Color containerColor, Color borderColor) {
    return BoxDecoration(
      color: containerColor,
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(6)),
      border: Border.fromBorderSide(BorderSide(
        color: borderColor,
        width: 2.0,
      )),
    );
  }
}
