import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.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/LiveCarePatientViewModel.dart';
import 'package:doctor_app_flutter/core/viewModel/project_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/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/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/button_bottom_sheet.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:provider/provider.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;

class LivaCareTransferToAdmin extends StatefulWidget {
  final PatiantInformtion? patient;

  const LivaCareTransferToAdmin({Key? key, this.patient}) : super(key: key);

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

class _LivaCareTransferToAdminState extends State<LivaCareTransferToAdmin> {
  stt.SpeechToText speech = stt.SpeechToText();
  var recognizedWord;
  var event = RobotProvider();
  late ProjectViewModel projectViewModel;

  TextEditingController noteController = TextEditingController();
  String? noteError;

  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) {
    projectViewModel = Provider.of(context);

    return BaseView<LiveCarePatientViewModel>(
      onModelReady: (model) {},
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        appBarTitle: "${TranslationBase.of(context).transferTo}${TranslationBase.of(context).admin}",
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        isShowAppBar: true,
        body: Container(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.all(16),
                    child: Stack(
                      children: [
                        AppTextFieldCustom(
                          hintText: TranslationBase.of(context).notes,
                          //TranslationBase.of(context).addProgressNote,
                          controller: noteController,
                          maxLines: 35,
                          minLines: 25,
                          hasBorder: true,
                          validationError: noteError!,
                          onClick: () {},

                          onFieldSubmitted: () {},
                          onChanged: (String? value) {},
                        ),
                        Positioned(
                            top: -2,
                            //MediaQuery.of(context).size.height * 0,
                            right: projectViewModel.isArabic ? MediaQuery.of(context).size.width * 0.75 : 15,
                            child: Column(
                              children: [
                                IconButton(
                                  icon: Icon(DoctorApp.speechtotext, color: Colors.black, size: 35),
                                  onPressed: () {
                                    initSpeechState().then((value) => {onVoiceText()});
                                  },
                                ),
                              ],
                            ))
                      ],
                    ),
                  ),
                ),
              ),
              ButtonBottomSheet(
                title: "${TranslationBase.of(context).transferTo}${TranslationBase.of(context).admin}",
                onPressed: () {
                  setState(() {
                    if (noteController.text.isEmpty) {
                      noteError = TranslationBase.of(context).emptyMessage;
                    } else {
                      noteError = null;
                    }
                    if (noteController.text.isNotEmpty) {
                      Utils.showConfirmationDialog(context, "${TranslationBase.of(context).areYouSureYouWantTo} ${TranslationBase.of(context).transferTo}${TranslationBase.of(context).admin} ?",
                          () async {
                        Navigator.of(context).pop();
                        GifLoaderDialogUtils.showMyDialog(context);
                        await model.transferToAdmin(widget.patient!.vcId!, noteController.text);
                        GifLoaderDialogUtils.hideDialog(context);
                        if (model.state == ViewState.ErrorLocal) {
                          DrAppToastMsg.showErrorToast(model.error);
                        } else {
                          DrAppToastMsg.showSuccesToast("You successfully transfer to admin");
                          Navigator.of(context).pop();
                          Navigator.of(context).pop();
                          Navigator.of(context).pop();
                        }
                      });
                    }
                  });
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  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();
        noteController.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;
  }
}
