import 'dart:math';

import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/search_drug/get_medication_response_model.dart';
import 'package:doctor_app_flutter/core/viewModel/medicine_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/medicine/pharmacies_list_screen.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/utils/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.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/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/medicine/medicine_item_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app_text_field_custom_serach.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.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';

DrAppSharedPreferances sharedPref = DrAppSharedPreferances();

class MedicineSearchScreen extends StatefulWidget implements DrAppToastMsg {
  MedicineSearchScreen({this.changeLoadingState});

  final Function? changeLoadingState;

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

class _MedicineSearchState extends State<MedicineSearchScreen> {
  var data;
  final myController = TextEditingController();
  Utils helpers = new Utils();
  bool _hasSpeech = false;
  String _currentLocaleId = "";
  final SpeechToText speech = SpeechToText();
  String lastStatus = '';
  GlobalKey key = new GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>>();

  String? lastError;
  double level = 0.0;
  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String recognizedWord = '';

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  Future<void> initSpeechState() async {
    bool hasSpeech = await speech.initialize(onError: errorListener, onStatus: statusListener);
    _currentLocaleId = TranslationBase.of(context).locale.languageCode == 'en' ? 'en-GB' : 'ar-SA'; // systemLocale.localeId;
    if (!mounted) return;

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<MedicineViewModel>(
        onModelReady: (model) async {},
        builder: (_, model, w) {
          // myController.text = model.searchText;
          return AppScaffold(
            // baseViewModel: model,
            isShowAppBar: true,
            appBar: BottomSheetTitle(
              title: TranslationBase.of(context).searchMedicine,
            ),
            body: SingleChildScrollView(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                AppTextFieldCustomSearch(
                  hintText: TranslationBase.of(context).searchMedicineNameHere,
                  searchController: myController,
                  onFieldSubmitted: (value) {
                    searchMedicine(context, model);
                  },
                  marginTop: 5,
                  onChangeFun: (String val) {},
                ),
                Container(
                  margin: EdgeInsets.only(left: 16, right: 16, bottom: 16, top: 0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: AppText(
                          TranslationBase.of(context).youCanFind +
                              (myController.text != '' ? model.pharmacyItemsList.length.toString() : '0') +
                              " " +
                              TranslationBase.of(context).medicineSearchResult +
                              "  '${myController.text}'",
                          fontHeight: 1.4,
                          color: AppGlobal.appTextColor,
                          textAlign: TextAlign.start,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.9,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
                if (myController.text != '')
                  Container(
                    margin: EdgeInsets.only(left: 16, right: 16, bottom: 16, top: 0),
                    height: MediaQuery.of(context).size.height * 0.6,
                    child: ListView.builder(
                      padding: const EdgeInsets.only(top: 20),
                      scrollDirection: Axis.vertical,
                      itemCount: model.pharmacyItemsList == null ? 0 : model.pharmacyItemsList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return InkWell(
                          child: MedicineItemWidget(
                            label: model.pharmacyItemsList[index]["ItemDescription"],
                            url: model.pharmacyItemsList[index]["ImageSRCUrl"],
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => PharmaciesListScreen(itemID: model.pharmacyItemsList[index]["ItemID"], url: model.pharmacyItemsList[index]["ImageSRCUrl"]),
                                settings: RouteSettings(name: 'PharmaciesListScreen'),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  ),
              ],
            )),
            bottomSheet: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(0.0),
                ),
                border: Border.all(color: HexColor('#707070'), width: 0),
              ),
              height: MediaQuery.of(context).size.height * 0.1,
              width: double.infinity,
              child: Column(
                children: [
                  SizedBox(
                    height: 10,
                  ),
                  Container(
                    child: FractionallySizedBox(
                      widthFactor: .80,
                      child: Center(
                        child: AppButton(
                          fontWeight: FontWeight.w700,
                          title: TranslationBase.of(context).search,
                          onPressed: () async {
                            await searchMedicine(context, model);
                          },
                          color: AppGlobal.appRedColor,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                ],
              ),
            ),
          );
        });
  }

  searchMedicine(context, MedicineViewModel model) async {
    FocusScope.of(context).unfocus();
    if (myController.text.isNullOrEmpty()) {
      Utils.showErrorToast(TranslationBase.of(context).typeMedicineName);
      return;
    }
    if (myController.text.length < 3) {
      Utils.showErrorToast(TranslationBase.of(context).moreThan3Letter);
      return;
    }

    GifLoaderDialogUtils.showMyDialog(context);

    await model.getMedicineItem(myController.text);
    GifLoaderDialogUtils.hideDialog(context);
  }

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

  void resultListener(SpeechRecognitionResult result) {
    setState(() {
      recognizedWord = result.recognizedWords;
      lastStatus = '';
      myController.text = recognizedWord;
      Future.delayed(const Duration(seconds: 2), () {});
    });
  }

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

  void statusListener(String status) {
    // print(
    setState(() {
      lastStatus = status;
    });
  }

  void soundLevelListener(double level) {
    minSoundLevel = min(minSoundLevel, level);
    maxSoundLevel = max(maxSoundLevel, level);
    setState(() {
      this.level = level;
    });
  }
}
