import 'dart:collection';
import 'dart:math';

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorProfile.dart';
import 'package:hmg_patient_app/pages/BookAppointment/DoctorProfile.dart';
import 'package:hmg_patient_app/pages/BookAppointment/Search.dart';
import 'package:hmg_patient_app/pages/BookAppointment/widgets/BranchView.dart';
import 'package:hmg_patient_app/pages/ErService/NearestEr.dart';
import 'package:hmg_patient_app/pages/MyAppointments/MyAppointments.dart';
import 'package:hmg_patient_app/pages/feedback/feedback_home_page.dart';
import 'package:hmg_patient_app/pages/insurance/insurance_approval_screen.dart';
import 'package:hmg_patient_app/pages/insurance/insurance_update_screen.dart';
import 'package:hmg_patient_app/pages/livecare/livecare_home.dart';
import 'package:hmg_patient_app/pages/medical/doctor/doctor_home_page.dart';
import 'package:hmg_patient_app/pages/medical/labs/labs_home_page.dart';
import 'package:hmg_patient_app/pages/medical/patient_sick_leave_page.dart';
import 'package:hmg_patient_app/pages/medical/prescriptions/prescriptions_home_page.dart';
import 'package:hmg_patient_app/pages/medical/radiology/radiology_home_page.dart';
import 'package:hmg_patient_app/pages/medical/reports/report_home_page.dart';
import 'package:hmg_patient_app/pages/medical/vital_sign/vital_sign_details_screen.dart';
import 'package:hmg_patient_app/pages/vaccine/my_vaccines_screen.dart';
import 'package:hmg_patient_app/routes.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/robo_search/event_provider.dart';
import 'package:hmg_patient_app/services/robo_search/search_provider.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.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_recognition_result.dart';
// import 'package:speech_to_text/speech_to_text.dart';

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

class _SearchBot extends State<BottomBarSearch> {
  SearchProvider searchProvider = new SearchProvider();
  RobotProvider robotProvider = 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();
  ProjectViewModel? projectProvider;

  @override
  void initState() {
    requestPermissions();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectProvider = Provider.of(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'])});
  }

  getCommands(result) async {
    print(result);
    results = result;

    switch (result["CommandNumber"]) {
      case '100':
        {
          List clnicID = unique(result['ClinicId']);
          if (result['ProjectId'] != 0 && clnicID.length > 0 && result['DoctorId'].length > 0) {
            if (clnicID.length == 1) {
              getDoctorsList(
                result['ProjectId'],
                clnicID[0],
                context,
                doctorId: result['DoctorId'],
                doctorName: null,
              );
            } else {
              goToClinic(clnicID);
            }
          } else if (result['ProjectId'] != 0 && clnicID.length > 0 && result['DoctorId'].length == 0) {
            if (clnicID.length == 1) {
              getDoctorsList(
                result['ProjectId'],
                clnicID[0],
                context,
              );
            } else {
              goToClinic(clnicID);
            }
          } else if (result['ProjectId'] == 0 && clnicID.length > 0 && result['DoctorId'].length == 0) {
            if (clnicID.length == 1) {
              getDoctorsList(
                result['ProjectId'],
                clnicID[0],
                context,
              );
            } else {
              goToClinic(clnicID);
            }
          } else if (result['ProjectId'] == 0 && clnicID.length > 0 && result['DoctorId'].length > 0) {
            if (clnicID.length == 1) {
              getDoctorsList(
                result['ProjectId'],
                clnicID[0],
                context,
                doctorId: result['DoctorId'],
                doctorName: null,
              );
            } else {
              goToClinic(clnicID);
            }
          } else {
            goToClinic(clnicID);
          }
          // speak();
        }
        break;
      case '102':
        {
          getDoctorsList(
            0,
            0,
            context,
            doctorId: result['DoctorId'],
            doctorName: null,
          );
        }
        break;
      case '103':
        {
          List clnicID = unique(result['ClinicId']);
          if (clnicID.length == 1) {
            getDoctorsList(
              0,
              clnicID[0],
              context,
              doctorId: null,
              doctorName: null,
            );
          } else {
            goToClinic(clnicID);
          }
        }
        break;
      case '4':
        {
          Navigator.push(context, FadePage(page: LabsHomePage()));
        }
        break;
      case '6':
        {
          Navigator.push(context, FadePage(page: RadiologyHomePage()));
        }
        break;
      case '7':
        {
          Navigator.push(
            context,
            FadePage(
              page: MyAppointments(),
            ),
          );
        }
        break;
      case '8':
        {
          Navigator.push(
            context,
            FadePage(
              page: HomePrescriptionsPage(),
            ),
          );
        }
        break;
      case '9':
        {
          Navigator.push(
            context,
            FadePage(
              page: DoctorHomePage(),
            ),
          );
        }
        break;
      case '10':
        {
          Navigator.push(
            context,
            FadePage(
              page: VitalSignDetailsScreen(),
            ),
          );
        }
        break;
      case '11':
        {
          Navigator.push(context, FadePage(page: InsuranceUpdate()));
        }
        break;
      case '12':
        {
          Navigator.push(context, FadePage(page: InsuranceApproval(appointmentNo: 0,)));
        }
        break;
      case '13':
        {
          Navigator.push(context, FadePage(page: MyVaccines()));
        }
        break;
      case '14':
        {
          Navigator.push(context, FadePage(page: HomeReportPage()));
        }
        break;
      case '5':
        {
          Navigator.push(context, FadePage(page: NearestEr()));
        }
        break;
      case '15':
        {
          Navigator.push(context, FadePage(page: PatientSickLeavePage()));
        }
        break;
      case '16':
        {
          Navigator.push(context, FadePage(page: LiveCareHome()));
        }
        break;

      case '200':
        {
          Navigator.push(context, FadePage(page: FeedbackHomePage()));
        }
        break;

      default:
        Navigator.of(context).pushNamed(HOME);
        speak();
        break;
    }

    //searchProvider.setLisener(result);
  }

  getDoctorProfile(projectId, clinicId, doctorId, context, doctorData) {
    int languageID = projectProvider!.isArabic ? 1 : 2;
    List<DoctorProfileList> docProfileList = [];
    DoctorsListService service = new DoctorsListService();

    service.getDoctorsProfile(doctorId, clinicId, projectId, languageID, 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);
    });
  }

  getDoctorsList(projectId, clinicId, context, {doctorId, doctorName}) {
    int languageID = projectProvider!.isArabic ? 1 : 2;
    List<DoctorList> doctorsList = [];
    List<String> arr = [];
    List<String> arrDistance = [];
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getDoctorsList(clinicId, projectId, false, languageID, context, doctorId: doctorId, doctorName: doctorName).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['SearchDoctorsByTime_IsVoiceCommandList'] != null && res['SearchDoctorsByTime_IsVoiceCommandList'].length != 0) {
            doctorsList.clear();
            res['SearchDoctorsByTime_IsVoiceCommandList'].forEach((v1) {
              v1['DoctorList'].forEach((v) {
                doctorsList.add(new DoctorList.fromJson(v));
                  arr.add(new DoctorList.fromJson(v).projectName!);
                arrDistance.add(new DoctorList.fromJson(v)
                    .projectDistanceInKiloMeters
                    .toString());
              });
            });
            if (doctorsList.length == 1) {
              getDoctorProfile(projectId, clinicId, doctorId[0], context, doctorsList);

              //speak();
            } else {
              navigateToSearchResults(context, doctorsList, arr, arrDistance);
            }
          } else if (res['DoctorList'].length != 0) {
            doctorsList.clear();

            res['DoctorList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
               arr.add(new DoctorList.fromJson(v).projectName!);
              arrDistance.add(new DoctorList.fromJson(v)
                  .projectDistanceInKiloMeters
                  .toString());
            });

            if (doctorsList.length == 1) {
              getDoctorProfile(projectId, clinicId, doctorId[0], context, doctorsList);

              //speak();
            } else {
              navigateToSearchResults(context, doctorsList, arr, arrDistance);
            }
          }
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  Future navigateToDoctorProfile(context, docObject, docProfile, {isAppo}) async {
    Navigator.push(
        context,
        FadePage(
            page: DoctorProfile(
          doctor: docObject,
          docProfileList: docProfile,
          isOpenAppt: isAppo, isLiveCareAppointment: false,
        )));
  }

  Future navigateToSearchResults(context, docList, arr, arrDistance) async {
    var result = LinkedHashSet<String>.from(arr).toList();
    var numAll = result.length;
    Navigator.push(
      context,
      FadePage(
        page: BranchView(doctorsList: docList, result: result, num: numAll, resultDistance: arrDistance),
      ),
    );
  }

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

  goToClinic(List ids) {
    Navigator.push(
        AppGlobal.context,
        FadePage(
            page: Search(
          type: 0,
          clnicIds: ids,
        )));
    speak();
  }

  List unique(List list) {
    return list.toSet().toList();
  }
}
