import 'dart:async';

import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/provider/robot_provider.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/utils/extenstions_utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;

class SpeechToText {
  final BuildContext context;
  static var dialog;
  static stt.SpeechToText speech = stt.SpeechToText();

  SpeechToText({
    required this.context,
  });

  showAlertDialog(BuildContext context) {
    // show the dialog
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        dialog = context;
        return MyStatefulBuilder(
          dispose: () {},
        );
      },
    );
    print(dialog);
  }

  static closeAlertDialog(BuildContext context) {
    Navigator.of(dialog).pop();
    speech.stop();
  }
}

typedef Disposer = void Function();

class MyStatefulBuilder extends StatefulWidget {
  const MyStatefulBuilder({
    // @required this.builder,
    required this.dispose,
  });

  //final StatefulWidgetBuilder builder;
  final Disposer dispose;

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

class _MyStatefulBuilderState extends State<MyStatefulBuilder> {
  var event = RobotProvider();
  var searchText;
  late  StreamSubscription<dynamic> streamSubscription;
  static var isClosed = false;

  @override
  void initState() {
 startStreamListener();
    super.initState();
  }

  @override
  Widget build(BuildContext context) => AlertDialog(
      content: Container(
          color: Colors.white,
          height: SizeConfig.realScreenHeight! * 0.5,
          width: SizeConfig.realScreenWidth! * 0.8,
          child: Container(
            child: Column(children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  IconButton(
                      icon: Icon(DoctorApp.close),
                      onPressed: () {
                        SpeechToText.closeAlertDialog(context);
                      })
                ],
              ),
              Expanded(
                  flex: 3,
                  child: Center(
                      child: Container(
                    margin: EdgeInsets.all(20),
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(100), border: Border.all(width: 2, color: Colors.red)),
                    child: Icon(
                      Icons.mic,
                      color: Colors.blue,
                      size: 48,
                    ),
                  ))),
              Expanded(
                  flex: 1,
                  child: Center(
                      child: Image.asset(
                    'assets/images/soundWaveAnimation.gif',
                    height: 75,
                  ))),
              Expanded(
                  flex: 1,
                  child: Center(
                      child: AppText(
                    searchText == null
                        ? TranslationBase.of(context).trySaying
                        : searchText == 'null'
                            ? TranslationBase.of(context).didntCatch
                            : searchText,
                    fontSize: 14,
                  ))),
              searchText == 'null'
                  ? Center(
                      child: InkWell(
                      child: Container(
                          decoration: BoxDecoration(border: Border.all(color: Colors.grey[300]!)),
                          padding: EdgeInsets.all(5),
                          child: AppText(
                            'Try Again',
                            fontSize: 13,
                          )),
                      onTap: () {
                        SpeechToText.closeAlertDialog(context);
                        event.setValue({'startPopUp': 'true'});
                      },
                    ))
                  : SizedBox(),
              Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                Image.asset(
                  'assets/images/habib-logo.png',
                  height: 20,
                  width: 20,
                )
              ])
            ]),
          )));

  @override
  void dispose() {
    widget.dispose();
    streamSubscription.cancel();
    super.dispose();
  }

  void startStreamListener() {
    streamSubscription = event.controller.stream.listen((p) {
      if ((p['searchText'] != 'null' && p['searchText'] != null && p['searchText'] != "" && isClosed == false && mounted)) {
        setState(() {
          searchText = p['searchText'];
          // SpeechToText.closeAlertDialog(context);
        });
      } else if (p['searchText'] == 'null' && mounted) {
        setState(() {
          searchText = p['searchText'];
        });
      }
    });
  }
}
