import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/model/note/CreateNoteModel.dart';
import 'package:doctor_app_flutter/core/model/note/note_model.dart';
import 'package:doctor_app_flutter/core/model/note/update_note_model.dart';
import 'package:doctor_app_flutter/core/provider/robot_provider.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/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/models/patient/progress_note_request.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.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/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.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: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;

class UpdateNoteOrder extends StatefulWidget {
  final NoteModel note;
  final PatientViewModel patientModel;
  final PatiantInformtion patient;
  final int visitType;
  final bool isUpdate;

  const UpdateNoteOrder(
      {Key key,
      this.note,
      this.patientModel,
      this.patient,
      this.visitType,
      this.isUpdate})
      : super(key: key);

  @override
  _UpdateNoteOrderState createState() => _UpdateNoteOrderState();
}

class _UpdateNoteOrderState extends State<UpdateNoteOrder> {
  int selectedType;
  bool isSubmitted = false;
  stt.SpeechToText speech = stt.SpeechToText();
  var reconizedWord;
  var event = RobotProvider();
  TextEditingController progressNoteController = TextEditingController();

  setSelectedType(int val) {
    setState(() {
      selectedType = val;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (widget.note != null) {
      progressNoteController.text = widget.note.notes;
    }

    return AppScaffold(
      isShowAppBar: false,
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height * 1.0,
          child: Padding(
            padding: EdgeInsets.all(0.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                BottomSheetTitle(
                  title: widget.visitType == 3
                      ? (widget.isUpdate ? 'Update' : 'Add') + ' Order Sheet'
                      : (widget.isUpdate ? 'Update' : 'Add') + ' Progress Note',
                ),
                SizedBox(
                  height: 10.0,
                ),
                Center(
                  child: FractionallySizedBox(
                    widthFactor: 0.9,
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            AppTextFieldCustom(
                              hintText: widget.visitType == 3
                                  ? (widget.isUpdate ? 'Update' : 'Add') +
                                      ' Order Sheet'
                                  : (widget.isUpdate ? 'Update' : 'Add') +
                                      ' Progress Note',
                              //TranslationBase.of(context).addProgressNote,
                              controller: progressNoteController,
                              maxLines: 35,
                              minLines: 25,
                              hasBorder: true,

                              // isTextFieldHasSuffix: true,
                              validationError:
                                  progressNoteController.text.isEmpty &&
                                          isSubmitted
                                      ? TranslationBase.of(context).emptyMessage
                                      : null,
                            ),
                            Positioned(
                              top: 0, //MediaQuery.of(context).size.height * 0,
                              right: 15,
                              child: IconButton(
                                icon: Icon(
                                  DoctorApp.speechtotext,
                                  color: Colors.black,
                                ),
                                onPressed: () {
                                  initSpeechState()
                                      .then((value) => {onVoiceText()});
                                },
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      bottomSheet: Container(
        margin: EdgeInsets.all(SizeConfig.widthMultiplier * 5),
        child: Wrap(
          alignment: WrapAlignment.center,
          children: <Widget>[
            AppButton(
                title: widget.visitType == 3
                    ? (widget.isUpdate ? 'Update' : 'Add') + ' Order Sheet'
                    : (widget.isUpdate ? 'Update' : 'Add') + ' Progress Note',
                color: Color(0xff359846),
                // disabled: progressNoteController.text.isEmpty,
                fontWeight: FontWeight.w700,
                onPressed: () async {
                  setState(() {
                    isSubmitted = true;
                  });
                  if (progressNoteController.text.trim().isNotEmpty) {
                    GifLoaderDialogUtils.showMyDialog(context);
                    Map profile = await sharedPref.getObj(DOCTOR_PROFILE);

                    DoctorProfileModel doctorProfile =
                        DoctorProfileModel.fromJson(profile);

                    if (widget.isUpdate) {
                      UpdateNoteReqModel reqModel = UpdateNoteReqModel(
                        admissionNo: int.parse(widget.patient.admissionNo),
                        cancelledNote: false,
                        lineItemNo: widget.note.lineItemNo,
                        createdBy: widget.note.createdBy,
                        notes: progressNoteController.text,
                        verifiedNote: false,
                        patientTypeID: widget.patient.patientType,
                        patientOutSA: false,
                      );
                      await widget.patientModel
                          .updatePatientProgressNote(reqModel);
                    } else {
                      CreateNoteModel reqModel = CreateNoteModel(
                          admissionNo: int.parse(widget.patient.admissionNo),
                          createdBy: doctorProfile.doctorID,
                          visitType: widget.visitType,
                          patientID: widget.patient.patientId,
                          nursingRemarks: '  ',
                          patientTypeID: widget.patient.patientType,
                          patientOutSA: false,
                          notes: progressNoteController.text);

                      await widget.patientModel
                          .createPatientProgressNote(reqModel);
                    }

                    if (widget.patientModel.state == ViewState.ErrorLocal) {
                      Helpers.showErrorToast(widget.patientModel.error);
                    } else {
                      ProgressNoteRequest progressNoteRequest =
                          ProgressNoteRequest(
                              visitType: widget.visitType,
                              // if equal 5 then this will return progress note
                              admissionNo:
                                  int.parse(widget.patient.admissionNo),
                              projectID: widget.patient.projectId,
                              patientTypeID: widget.patient.patientType,
                              languageID: 2);
                      await widget.patientModel
                          .getPatientProgressNote(progressNoteRequest.toJson());
                    }
                    GifLoaderDialogUtils.hideDialog(context);
                    DrAppToastMsg.showSuccesToast(
                        "Your Order added Successfully");
                    Navigator.of(context).pop();
                  } else {
                    Helpers.showErrorToast("You cant add only spaces");
                  }
                }),
          ],
        ),
      ),
    );
  }

  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) {
    reconizedWord = status == 'listening' ? 'Lisening...' : 'Sorry....';
  }

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

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

    if (result.finalResult == true) {
      setState(() {
        SpeechToText.closeAlertDialog(context);
        speech.stop();
        progressNoteController.text = reconizedWord;
      });
    } else {
      print(result.finalResult);
    }
  }

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