import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/provider/robot_provider.dart';
import 'package:doctor_app_flutter/core/viewModel/base_view_model.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/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/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 AddVerifyMedicalReport extends StatefulWidget {
  final MedicalReportStatus status;

  AddVerifyMedicalReport(this.status);

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

class _AddVerifyMedicalReportState extends State<AddVerifyMedicalReport> {
  stt.SpeechToText speech = stt.SpeechToText();
  var reconizedWord;
  var event = RobotProvider();

  TextEditingController commentController = TextEditingController();
  String commentsError;

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

    return BaseView<BaseViewModel>(
        builder: (_, model, w) => AppScaffold(
              baseViewModel: model,
              isShowAppBar: true,
              appBarTitle: widget.status == MedicalReportStatus.ADD
                  ? TranslationBase.of(context).medicalReportAdd
                  : TranslationBase.of(context).medicalReportVerify,
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,
              body: Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Stack(
                              children: [
                                AppTextFieldCustom(
                                  hintText: TranslationBase.of(context)
                                      .sickLeaveComments,
                                  controller: commentController,
                                  maxLines: 30,
                                  minLines: 20,
                                  hasBorder: true,
                                  validationError: commentsError,
                                ),
                                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()});
                                          },
                                        ),
                                      ],
                                    )),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.all(16.0),
                    child: AppButton(
                      title: widget.status == MedicalReportStatus.ADD
                          ? TranslationBase.of(context).medicalReportAdd
                          : TranslationBase.of(context).medicalReportVerify,
                      color: Color(0xff359846),
                      // disabled: progressNoteController.text.isEmpty,
                      fontWeight: FontWeight.w700,
                      onPressed: () {
                        setState(() {
                          if (commentController.text == "") {
                            commentsError =
                                TranslationBase.of(context).fieldRequired;
                          } else {
                            commentsError = null;
                          }
                        });
                      },
                    ),
                  ),
                ],
              ),
            ));
  }

  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();
        commentController.text += reconizedWord + '\n';
      });
    } else {
      print(result.finalResult);
    }
  }

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

enum MedicalReportStatus { ADD, VERIFY }
