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/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:flutter/material.dart';
import 'package:html_editor_enhanced/html_editor.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;

import '../speech-text-popup.dart';

class HtmlRichEditor extends StatefulWidget {
  final String hint;
  final String? initialText;
  final double height;
  final BoxDecoration? decoration;
  final bool darkMode;
  final bool showBottomToolbar;
  final List<Toolbar>? toolbar;
  final HtmlEditorController? controller;

  HtmlRichEditor({
    key,
    this.hint = "Your text here...",
    this.initialText,
    this.height = 400,
    this.decoration,
    this.darkMode = false,
    this.showBottomToolbar = false,
    this.toolbar,
    this.controller,
  }) : super(key: key);

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

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

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

    return Stack(
      children: [
        HtmlEditor(
            controller: widget.controller!,
            htmlToolbarOptions: HtmlToolbarOptions(defaultToolbarButtons: [
              StyleButtons(),
              FontSettingButtons(),
              FontButtons(),
              // ColorButtons(),
              ListButtons(),
              ParagraphButtons(),
              // InsertButtons(),
              // OtherButtons(),
            ]),
            htmlEditorOptions: HtmlEditorOptions(
              hint: widget.hint,
              initialText: widget.initialText,
              darkMode: widget.darkMode,
            ),
            otherOptions: OtherOptions(
              height: widget.height,
              decoration: widget.decoration ??
                  BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.all(
                      Radius.circular(30.0),
                    ),
                    border: Border.all(color: Colors.grey[200]!, width: 0.5),
                  ),
            )),
        Positioned(
            top: 50, //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()});
                  },
                ),
              ],
            ))
      ],
    );
  }

  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) async {
    recognizedWord = result.recognizedWords;
    event.setValue({"searchText": recognizedWord});
    String txt = await widget.controller!.getText();
    if (result.finalResult == true) {
      setState(() {
        widget.controller!.setText(txt + recognizedWord);
        SpeechToText.closeAlertDialog(context);
        //  speech.stop();
      });
    } else {
      print(result.finalResult);
    }
  }

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