import 'dart:convert';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorProfile.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/BookingOptions.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/DoctorProfile.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/Search.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/pages/medical/my_admissions_page.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/robo_search/search_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/bottom_navigation/bottom_nav_bar.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:diplomaticquarterapp/widgets/robo-search/robosearch.dart';
import 'dart:math';
import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:smart_progress_bar/smart_progress_bar.dart';

class BottomBarSearch extends StatefulWidget {
  @override
  _SearchBot createState() => _SearchBot();
}

class _SearchBot extends State<BottomBarSearch> {
  SearchProvider searchProvider = new SearchProvider();
  RobotProvider eventProvider = RobotProvider();
  bool isLoading = false;
  bool isError = false;
  final SpeechToText speech = SpeechToText();
  String error = '';
  String _currentLocaleId = "";
  String lastError;
  double level = 0.0;

  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String reconizedWord = '';
  FlutterTts flutterTts = FlutterTts();
  var selectedLang;
  bool isSearching = false;
  Map results = {};
  String lastStatus;

  bool _isInit = true;
  TextEditingController searchController = TextEditingController();
  @override
  void initState() {
    requestPermissions();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BottomAppBar(
      child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              child: SizedBox(
                height: 64,
                child: Material(
                  type: MaterialType.transparency,
                  child: TextField(
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    controller: searchController,
                    decoration: InputDecoration(
                        hintText: TranslationBase.of(context).textToSpeech,
                        suffixIcon: IconButton(
                          icon: Icon(Icons.mic),
                          onPressed: () async {
                            setState(() {
                              searchController.text = '';
                            });
                            // await flutterTts.speak("Hello!");
                            //Future.delayed(const Duration(seconds: 1), () {
                            initSpeechState()
                                .then((value) => startVoiceSearch());
                            //});
                          },
                        )),
                  ),
                ),
              ),
            ),
          ]),
    );
  }

  startVoiceSearch() async {
    speech.listen(
        onResult: resultListener,
        listenFor: Duration(seconds: 10),
        localeId: _currentLocaleId,
        onSoundLevelChange: soundLevelListener,
        cancelOnError: true,
        partialResults: true,
        onDevice: true,
        listenMode: ListenMode.confirmation);
  }

  void resultListener(SpeechRecognitionResult result) {
    // lastWords = "${result.recognizedWords} - ${result.finalResult}";

    if (result.finalResult == true) {
      // setState(() {
      reconizedWord = result.recognizedWords;
      //});
      setState(() {
        searchController.text = reconizedWord;
      });
      Future.delayed(const Duration(seconds: 1), () {
        _speak(reconizedWord);
      });
    }
    //});
  }

  Future _speak(reconizedWord) async {
    await flutterTts.speak(reconizedWord);

    getPages(reconizedWord);
  }

  void soundLevelListener(double level) {
    minSoundLevel = min(minSoundLevel, level);
    maxSoundLevel = max(maxSoundLevel, level);
    // print("sound level $level: $minSoundLevel - $maxSoundLevel ");
    //setState(() {
    this.level = level;
    // });
  }

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

  Future<void> initSpeechState() async {
    await speech.initialize(onError: errorListener, onStatus: statusListener);

    _currentLocaleId =
        TranslationBase.of(AppGlobal.context).locale.languageCode == 'en'
            ? 'en-GB'
            : 'ar-SA'; // systemLocale.localeId;
    flutterTts.setLanguage(_currentLocaleId);

    // if (!mounted) return;
  }

  void errorListener(SpeechRecognitionError error) {
    //setState(() {
    // reconizedWord = "${error.errorMsg} - ${error.permanent}";
    //});
  }

  void statusListener(String status) {
    //setState(() {
    reconizedWord = status == 'listening' ? 'Lisening...' : 'Sorry....';

    //});
  }

  getPages(text) {
    var request = {
      'VoiceMessage': text,
      'Lang': TranslationBase.of(AppGlobal.context).locale.languageCode == 'en'
          ? 'En'
          : 'Ar'
    };

    searchProvider
        .getBotPages(request)
        .then((value) => {getCommands(value['Understand'])});
    //getDoctorsList(12, 17, 40036, context);
  }

  getCommands(result) async {
    //RoboSearch.closeAlertDialog(context);
    print(result);
    results = result;
    //getDoctorsList(12, 17, 40036, context);

    switch (result["CommandNumber"]) {
      case 100:
        if (result['ProjectId'] != 0 &&
            result['ClinicId'] != 0 &&
            result['DoctorId'] != 0) {
          getDoctorsList(
            result['ProjectId'],
            result['ClinicId'],
            context,
            doctorId: result['DoctorId'],
            doctorName: result['DoctorName'],
          );
        } else if (result['ProjectId'] != 0 &&
            result['ClinicId'] != 0 &&
            result['DoctorId'] == 0) {
          getDoctorsList(
            result['ProjectId'],
            result['ClinicId'],
            context,
          );
        } else if (result['ProjectId'] == 0 &&
            result['ClinicId'] != 0 &&
            result['DoctorId'] == 0) {
          getDoctorsList(
            result['ProjectId'],
            result['ClinicId'],
            context,
          );
        } else if (result['ProjectId'] == 0 &&
            result['ClinicId'] != 0 &&
            result['DoctorId'] != 0) {
          getDoctorsList(
            result['ProjectId'],
            result['ClinicId'],
            context,
            doctorId: result['DoctorId'],
            doctorName: result['DoctorName'],
          );
        } else {
          Navigator.push(
              AppGlobal.context,
              MaterialPageRoute(
                  builder: (context) => Search(
                        type: 0,
                      )));
        }
        speak();
        break;
      // case '101':
      //   Navigator.push(
      //       AppGlobal.context,
      //       MaterialPageRoute(
      //           builder: (context) => Search(
      //                 type: 0,
      //               )));
      //   break;
      // case '102':
      //   Navigator.push(
      //       AppGlobal.context,
      //       MaterialPageRoute(
      //           builder: (context) => Search(
      //                 type: 1,
      //               )));
      //   break;
      // case '103':
      //   eventProvider.setValue({"clinic_id": understand});
      //   break;

      // case '104':
      //   eventProvider.setValue({"project_id": understand});
      //   break;
      // case '105':
      //   eventProvider.setValue({"doctor_id": understand});
      //   break;
      default:
        Navigator.of(context).pushNamed(HOME);
        speak();
        break;
    }

    //searchProvider.setLisener(result);
  }

  getDoctorProfile(projectId, clinicId, doctorId, context, doctorData) {
    List<DoctorProfileList> docProfileList = [];
    DoctorsListService service = new DoctorsListService();

    service
        .getDoctorsProfile(doctorId, clinicId, projectId, context)
        .then((res) {
      if (res['MessageStatus'] == 1) {
        if (res['DoctorProfileList'].length != 0) {
          res['DoctorProfileList'].forEach((v) {
            docProfileList.add(new DoctorProfileList.fromJson(v));
          });
        }

        navigateToDoctorProfile(context, doctorData[0], docProfileList[0],
            isAppo: true);
        //speak();
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  getDoctorsList(projectId, clinicId, context, {doctorId, doctorName}) {
    List<DoctorList> doctorsList = [];
    DoctorsListService service = new DoctorsListService();
    service
        .getDoctorsList(clinicId, projectId, false, context, doctorId: doctorName)
        .then((res) {
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorList'].length != 0) {
            doctorsList.clear();
            res['DoctorList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
            });
            if (res['DoctorList'].length == 1 && doctorId != null) {
              getDoctorProfile(
                  projectId, clinicId, doctorId, context, doctorsList);

              //speak();
            } else {
              navigateToSearchResults(context, doctorsList);
            }
          }
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(
            text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  Future navigateToDoctorProfile(context, docObject, docProfile,
      {isAppo}) async {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DoctorProfile(
                  doctor: docObject,
                  docProfileList: docProfile,
                  isOpenAppt: isAppo,
                )));
  }

  Future navigateToSearchResults(context, docList) async {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => SearchResults(doctorsList: docList)));
  }

  speak() async {
    if (_currentLocaleId == 'en-GB' && results['ReturnMessage'] != null) {
      await flutterTts.speak(results['ReturnMessage']);
    } else if (results['ReturnMessage_Ar'] != null) {
      await flutterTts.speak(results['ReturnMessage_Ar']);
    }
    // Future.delayed(const Duration(seconds: 10), () {
    //   initSpeechState().then((value) => startVoiceSearch());
    // });
  }
}
