import 'dart:collection';
import 'dart:io';
import 'dart:math';
import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.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/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/my_web_view.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/parking_page.dart';
import 'package:diplomaticquarterapp/pages/Blood/blood_donation.dart';
import 'package:diplomaticquarterapp/pages/Blood/my_balance_page.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/BranchView.dart';
import 'package:diplomaticquarterapp/pages/ContactUs/findus/findus_page.dart';
import 'package:diplomaticquarterapp/pages/DrawerPages/family/my-family.dart';
import 'package:diplomaticquarterapp/pages/ErService/AmbulanceReq.dart';
import 'package:diplomaticquarterapp/pages/ErService/ErOptions.dart';
import 'package:diplomaticquarterapp/pages/ErService/NearestEr.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/MyAppointments.dart';
import 'package:diplomaticquarterapp/pages/feedback/feedback_home_page.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_approval_screen.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_update_screen.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_home.dart';
import 'package:diplomaticquarterapp/pages/login/welcome.dart';
import 'package:diplomaticquarterapp/pages/medical/balance/advance_payment_page.dart';
import 'package:diplomaticquarterapp/pages/medical/doctor/doctor_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/labs/labs_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/medical_profile_page.dart';
import 'package:diplomaticquarterapp/pages/medical/patient_sick_leave_page.dart';
import 'package:diplomaticquarterapp/pages/medical/prescriptions/prescriptions_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/radiology/radiology_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/reports/report_home_page.dart';
import 'package:diplomaticquarterapp/pages/medical/vital_sign/vital_sign_details_screen.dart';
import 'package:diplomaticquarterapp/pages/paymentService/payment_service.dart';
import 'package:diplomaticquarterapp/pages/vaccine/my_vaccines_screen.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart';
import 'package:diplomaticquarterapp/services/robo_search/search_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/robo-search/robosearch.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.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';
import 'package:diplomaticquarterapp/pages/BookAppointment/DoctorProfile.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/Search.dart';
import 'package:flutter/cupertino.dart';

import 'package:smart_progress_bar/smart_progress_bar.dart';
import 'package:url_launcher/url_launcher.dart';

class FloatingSearchButton extends StatefulWidget {
  @override
  _FloatingSearchButton createState() => _FloatingSearchButton();
}

class _FloatingSearchButton extends State<FloatingSearchButton>
    with TickerProviderStateMixin {
  Offset position = Offset(250, 400);
  bool activeAnimation = false;
  bool isShow = true;
  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;
  var searchText;
  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String reconizedWord = '';
  FlutterTts flutterTts = FlutterTts();
  var selectedLang;
  bool isSearching = false;
  Map results = {};
  String lastStatus;
  AuthenticatedUser user;
  bool _isInit = true;
  var event = RobotProvider();
  var sharedPref = new AppSharedPreferences();
  bool _hasSpeech = false;
  ProjectViewModel projectProvider;

  @override
  void initState() {
    event.controller.stream.listen((p) {
      if (p['isRobot'] == 'true') {
        if (this.mounted) {
          setState(() {
            position = Offset(250, 400);
            activeAnimation = false;
          });
        }
      }
    });

    Future.delayed(const Duration(seconds: 2), () {
      // _currentLocaleId =
      //     TranslationBase.of(AppGlobal.context).locale.languageCode == 'en'
      //         ? 'en-US'
      //         : 'ar-SA';
      requestPermissions();

      getUserData();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectProvider = Provider.of(context);
    return AnimatedPositioned(
        onEnd: () {
          // setState(() {
          //   this.isShow = false;
          //   position = Offset(250, 400);
          // });
        },
        left: activeAnimation
            ? TranslationBase.of(AppGlobal.context).locale.languageCode == 'en'
                ? 300
                : 0
            : position.dx,
        top: activeAnimation ? -150 : position.dy,
        duration: activeAnimation
            ? const Duration(seconds: 1)
            : const Duration(seconds: 0),
        // curve: Curves.bounceOut,
        child: isShow
            ? Draggable(
                feedback: Container(child: getStack()),
                child: getStack(),
                childWhenDragging: Container(
                  color: Colors.transparent,
                ),
                onDragEnd: (details) {
                  setState(() {
                    position = details.offset;
                  });
                })
            : Container());

    // Draggable(
    //     feedback: getStack(),
    //     childWhenDragging: Container(),
    //     child: getStack(),
    //     onDragEnd: (drag) {
    //       setState(() {
    //         top = top + drag.offset.dy < 0 ? 0 : top + drag.offset.dy;
    //         left = left + drag.offset.dx < 0 ? 0 : left + drag.offset.dx;
    //       });
    //     });
  }

  Widget getStack() {
    return Container(
        height: 150,
        width: 150,
        child: Stack(children: <Widget>[
          // Column(
          // mainAxisSize: MainAxisSize.min,
          // crossAxisAlignment: CrossAxisAlignment.stretch,
          // children: <Widget>[
          GestureDetector(
            child: Container(
              child: Image.asset('assets/images/robort.png'),
            ),
            onTap: () {
              showDialog(
                  context: context,
                  builder: (_) {
                    return RoboSearch();
                  });
              initSpeechState().then((value) => {startVoiceSearch()});
            },
          ),
          // ],
          //   ),
          Positioned(
            right: 0.0,
            top: 10,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  if (this.mounted) {
                    activeAnimation = true;
                  }
                });
              },
              child: Align(
                alignment: Alignment.topRight,
                child: CircleAvatar(
                  radius: 14.0,
                  backgroundColor: Colors.red,
                  child: Icon(Icons.close, color: Colors.white),
                ),
              ),
            ),
          ),
        ]));
  }

  startVoiceSearch() async {
    _currentLocaleId =
        TranslationBase.of(AppGlobal.context).locale.languageCode;
    speech.listen(
        onResult: resultListener,
        listenFor: Duration(seconds: 10),
        localeId: _currentLocaleId == 'en' ? 'en-US' : 'ar-SA',
        onSoundLevelChange: soundLevelListener,
        cancelOnError: true,
        partialResults: true,
        onDevice: true,
        listenMode: ListenMode.deviceDefault);
  }

  void resultListener(SpeechRecognitionResult result) {
    // lastWords = "${result.recognizedWords} - ${result.finalResult}";
    print(result);
    reconizedWord = result.recognizedWords;
    event.setValue({"searchText": reconizedWord});
    if (result.finalResult == true) {
      // setState(() {

      // setState(() {
      //   searchText = reconizedWord;
      // });
      Future.delayed(const Duration(seconds: 1), () {
        _speak(reconizedWord);
      });
    }
    //});
  }

  Future _speak(reconizedWord) async {
    Navigator.of(AppGlobal.context).pop();
    //await flutterTts.speak(reconizedWord);
    //RoboSearch.closeAlertDialog(context);
    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 {
    bool hasSpeech = await speech.initialize(
        onError: errorListener, onStatus: statusListener);
    //if (hasSpeech) {
    // _currentLocaleId =
    // _currentLocaleId == 'en'
    //         ? 'en-US'
    //         : 'ar-SA'; // systemLocale.localeId;

    // }
    if (!mounted) return;

    // setState(() {
    //   _hasSpeech = hasSpeech;
    // });
  }

  void errorListener(SpeechRecognitionError error) {
    print(error);
    event.setValue({"searchText": 'null'});
    //setState(() {
    // reconizedWord = "${error.errorMsg} - ${error.permanent}";
    //});
  }

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

    //});
  }

  getPages(text) {
    var request = {
      'VoiceMessage': text,
      'Lang': _currentLocaleId == 'en' ? 'En' : 'Ar'
    };

    searchProvider
        .getBotPages(request)
        .then((value) => {getCommands(value['Understand'])});
  }

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

    switch (result["CommandNumber"]) {
      case '100':
        {
          getDoctorsList(
            result['ProjectId'],
            result['ClinicId'].length > 0 ? result['ClinicId'][0] : 0,
            context,
            doctorId: result['DoctorId'],
            doctorName: null,
          );

          // 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 '104':
        {
          List clnicID = unique(result['ClinicId']);
          //= result['ProjectId'] ? result['ProjectId'] : 0; //result['ProjectId'];

          if (clnicID.length == 1) {
            getDoctorsList(result['ProjectId'], clnicID[0], context,
                doctorId: null, doctorName: null, isNearest: true);
          } 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()));
        }
        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: MyBalancePage()));
        }
        break;
      case '17':
        {
          Navigator.push(context, FadePage(page: MedicalProfilePage()));
        }
        break;
      case '18':
        {
          //Drivethrough need to be implemeted here.

        }
        break;
      case '19':
        {
          Navigator.push(context, FadePage(page: LiveCareHome()));
        }
        break;
      case '20':
        {
          //CMC service need to be implemeted
        }
        break;
      case '21':
        {
          Navigator.push(context, FadePage(page: MyFamily()));
        }
        break;
      case '22':
        {
          Navigator.push(context, FadePage(page: BloodDonationPage()));
        }
        break;
      case '23':
        {
          //health calculator need to be implemeted
        }
        break;
      case '24':
        {
          Navigator.of(context).push(MaterialPageRoute(
              builder: (BuildContext context) => MyWebView(
                    title: "HMG News",
                    selectedUrl:
                        "https://twitter.com/hashtag/مجموعة_د_سليمان_الحبيب_الطبية?src=hashtag_click&f=live",
                  )));
        }
        break;
      case '25':
        {
          if (user == null) {
            Navigator.push(context, FadePage(page: WelcomeLogin()));
          }
        }
        break;
      case '26':
        {
          Navigator.push(context, FadePage(page: ParkingPage()));
        }
        break;
      case '27':
        {
          Navigator.push(
              context,
              FadePage(
                  page: ErOptions(
                isAppbar: true,
              )));
        }
        break;
      case '28':
        {
          Navigator.push(context, FadePage(page: AmbulanceReq()));
        }
        break;
      case '29':
        {
          Navigator.push(context, FadePage(page: FindUsPage()));
        }
        break;
      case '30':
        {
          launch("tel://" + result['PhoneNumbers'][0]);
        }
        break;
      case '31':
        {
          Navigator.of(context).popUntil(ModalRoute.withName('/'));
        }
        break;
      case '32':
        {
          Navigator.push(context, FadePage(page: AdvancePaymentPage()));
        }
        break;
      case '33':
        {
          if (result['LanguageCode'] != '0') {
            if (projectProvider.isArabic) {
              projectProvider.changeLanguage('en');
            } else {
              projectProvider.changeLanguage('ar');
            }
          }
        }
        break;
      case '34':
        {
          //settings page need to be implemented here
        }
        break;
      case '35':
        {
          if (Platform.isIOS) {
            launch(
                "https://apps.apple.com/sa/app/dr-suliaman-alhabib/id733503978");
          } else {
            launch(
                "https://play.google.com/store/apps/details?id=com.ejada.hmg&hl=en");
          }
        }
        break;
      case '36':
        {
          Navigator.of(context).pushNamed(
            REGISTER,
          );
        }
        break;
      case '37':
        {
          Navigator.of(context).pushNamed(
            SYMPTOM_CHECKER,
          );
        }
        break;
      case '38':
        {
          await this.sharedPref.setInt(IS_SEARCH_APPO, 1);
          Navigator.push(context, FadePage(page: MyAppointments()));
        }
        break;
      case '39':
        {
          await this.sharedPref.setInt(IS_SEARCH_APPO, 2);
          Navigator.push(context, FadePage(page: MyAppointments()));
        }
        break;
      case '40':
        {
          //Home health care service need to be implemeted here
        }
        break;
      case '41':
        {
          Navigator.push(context, FadePage(page: PaymentService()));
        }
        break;
      case '42':
        {
          //weather indicator  need to be implemented here

        }
        break;
      case '43':
        {
          await this.sharedPref.setInt(IS_SEARCH_APPO, 3);
          Navigator.push(context, FadePage(page: MyAppointments()));
        }
        break;
      case '44':
        {
          //chat need be implmented here.
        }
        break;
      case '45':
        {
          launch('https://hmg.com/ir/ar/Pages/ShareInformation/home.aspx');
        }
        break;
      case '46':
        {
          launch('https://hmg.com/ir/ar/pages/home.aspx');
        }
        break;
      case '200':
        {
          Navigator.push(context, FadePage(page: FeedbackHomePage()));
        }
        break;

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

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

  getDoctorsList(projectId, clinicId, context,
      {doctorId, doctorName, isNearest = false}) {
    List<DoctorList> doctorsList = [];
    List<String> arr = [];
    List<String> arrDistance = [];
    DoctorsListService service = new DoctorsListService();
    service
        .getDoctorsList(clinicId, projectId, isNearest, context,
            doctorId: doctorId, doctorName: doctorName)
        .then((res) {
      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) {
      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, arr, arrDistance) async {
    // Navigator.push(
    //     context,
    //     MaterialPageRoute(
    //         builder: (context) => SearchResults(doctorsList: docList)));
    var result = LinkedHashSet<String>.from(arr).toList();
    var numAll = result.length;
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BranchView(
            doctorsList: docList,
            result: result,
            num: numAll,
            resultDistance: arrDistance),
      ),
    );
  }

  speak() async {
    if (_currentLocaleId == 'en' && results['ReturnMessage'] != null) {
      await flutterTts.setVoice("en-us-x-sfg#male_2-local");
      await flutterTts.setLanguage("en-US");
      await flutterTts.speak(results['ReturnMessage']);
    } else if (results['ReturnMessage_Ar'] != null) {
      await flutterTts.setLanguage("ar-SA");

      await flutterTts.setVoice("ar-sa-x-sfg#male_1-local");
      await flutterTts.speak(results['ReturnMessage_Ar']);
    }
    // Future.delayed(const Duration(seconds: 10), () {
    //   initSpeechState().then((value) => startVoiceSearch());
    // });
  }

  goToClinic(List ids) {
    Navigator.push(
        AppGlobal.context,
        MaterialPageRoute(
            builder: (context) => Search(
                  type: 0,
                  clnicIds: ids,
                )));
    speak();
  }

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

  getUserData() async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      //setState(() async {
      user = AuthenticatedUser.fromJson(
          await this.sharedPref.getObject(USER_PROFILE));
      //  });
    }

    print(_currentLocaleId);
  }
}
