import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/model/Prescriptions/prescription_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/model/search_drug/get_medication_response_model.dart';
import 'package:doctor_app_flutter/core/provider/robot_provider.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/medicine_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/prescription/prescription_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/screens/prescription/prescription_text_filed.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.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/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/speech-text-popup.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/TextFields.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import '../../../core/model/SOAP/master_key_model.dart';

import '../../../widgets/transitions/slide_up_page.dart';
import 'add_drug/add_drug_widget.dart';

class PrescriptionFormWidget extends StatefulWidget {
  final PatiantInformtion patient;
  final List<PrescriptionModel> prescriptionList;
  final PrescriptionViewModel prescriptionViewModel;
  final MedicineViewModel medicineViewModel;
  final GetMedicationResponseModel selectedMedication;

  const PrescriptionFormWidget(
      {Key? key, required this.patient, required this.prescriptionList, required this.prescriptionViewModel, required this.medicineViewModel, required this.selectedMedication});

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

class _PrescriptionFormWidgetState extends State<PrescriptionFormWidget> {
  String? routeError;
  String? frequencyError;
  String? doseTimeError;
  String? durationError;
  String? unitError;
  String? strengthError;
  String? dateError;
  String? icdCodeError;
  int? selectedType;

  TextEditingController strengthController = TextEditingController();
  TextEditingController unitController = TextEditingController();
  TextEditingController indicationController = TextEditingController();
  TextEditingController instructionController = TextEditingController();

  bool visibilityPrescriptionForm = false;
  bool visibilitySearch = true;

  DateTime? selectedDate;
  int? strengthChar;
  GlobalKey key = new GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>>();

  TextEditingController drugIdController = TextEditingController();
  TextEditingController doseController = TextEditingController();
  final searchController = TextEditingController();
  stt.SpeechToText speech = stt.SpeechToText();
  var event = RobotProvider();
  var recognizedWord;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final double spaceBetweenTextFields = 12;
  dynamic route;
  dynamic frequency;
  dynamic duration;
  dynamic doseTime;
  dynamic units;
  dynamic uom;
  dynamic box;
  dynamic x;
  dynamic icdCode;
  TextEditingController icdNameController = TextEditingController();
  List<MasterKeyModel> icdCodeList =[];
  @override
  void initState() {
    getIcdCodeData();
    super.initState();
  }

  setSelectedType(int val) {
    setState(() {
      selectedType = val;
    });
  }

getIcdCodeData() async{
  await widget.prescriptionViewModel.getIcd10DISESECode(patient: widget.patient, itemID:widget.selectedMedication.itemId );
  icdCodeList = List.from(widget.prescriptionViewModel.icd10DeseaseItems);
}
  onVoiceText() async {
    new SpeechToText(context: context).showAlertDialog(context);
    var lang = TranslationBase.of(AppGlobal.CONTEX).locale.languageCode;
    bool available = await speech.initialize(onStatus: statusListener, onError: errorListener);
    if (available) {
      speech.listen(
        onResult: resultListener,
        listenMode: stt.ListenMode.confirmation,
        localeId: lang == 'en' ? 'en-US' : 'ar-SA',
      );
    } else {
      print("The user has denied the use of speech recognition.");
    }
  }

  void errorListener(SpeechRecognitionError error) {
    event.setValue({"searchText": 'null'});
    print(error);
  }

  void statusListener(String status) {
    recognizedWord = status == 'listening' ? 'Listening...' : 'Sorry....';
  }

  void resultListener(result) {
    recognizedWord = result.recognizedWords;
    event.setValue({"searchText": recognizedWord});

    if (result.finalResult == true) {
      setState(() {
        SpeechToText.closeAlertDialog(context);
        speech.stop();
        instructionController.text += recognizedWord + '\n';
      });
    } else {
      print(result.finalResult);
    }
  }

  Future<void> initSpeechState() async {
    bool hasSpeech = await speech.initialize(onError: errorListener, onStatus: statusListener);
    print(hasSpeech);
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Form(
      key: formKey,
      child: Column(
        children: [
          AppText(
            widget.selectedMedication.description ?? "",
            fontWeight: FontWeight.w600,
          ),
          SizedBox(
            height: 15.0,
          ),
          // Container(
          //   child:
          //   Row(
          //     mainAxisAlignment: MainAxisAlignment.start,
          //     children: [
          //       SizedBox(
          //         width: 6,
          //       ),
          //       AppText(
          //         TranslationBase.of(context).orderType,
          //         fontWeight: FontWeight.w500,
          //       ),
          //       SizedBox(
          //         width: 18,
          //       ),
          //       Radio(
          //         activeColor: AppGlobal.appRedColor,
          //         value: 1,
          //         groupValue: selectedType,
          //         onChanged: (value) {
          //           setSelectedType(value!);
          //         },
          //       ),
          //       Text(TranslationBase.of(context).regular),
          //     ],
          //   ),
          // ),
          Row(
            children: [
              Container(
                width: MediaQuery.of(context).size.width * 0.35,
                child: AppTextFieldCustom(
                  validationError: strengthError,
                  hintText: TranslationBase.of(context).strength,
                  isTextFieldHasSuffix: false,
                  enabled: true,
                  controller: strengthController,
                  onChanged: (value) {
                    setState(() {
                      strengthChar = value!.length;
                    });
                    if (strengthChar! >= 5) {
                      DrAppToastMsg.showErrorToast(
                        TranslationBase.of(context).only5DigitsAllowedForStrength,
                      );
                    }
                  },
                  inputType: TextInputType.numberWithOptions(
                    decimal: true,
                  ),
                  onFieldSubmitted: () {},
                ),
              ),
              SizedBox(
                width: 5.0,
              ),
              PrescriptionTextFiled(
                width: MediaQuery.of(context).size.width * 0.510,
                element: widget.medicineViewModel.itemMedicineListUnit.length == 1 ? units= widget.medicineViewModel.itemMedicineListUnit[0] : units,
                elementError: unitError,
                keyName: 'description',
                keyId: 'parameterCode',
                hintText: TranslationBase.of(context).unit,
                elementList: widget.medicineViewModel.itemMedicineListUnit,
                okFunction: (selectedValue) {
                  setState(() {
                    units = selectedValue;
                    units['isDefault'] = true;
                  });
                },
              ),
            ],
          ),
          SizedBox(height: spaceBetweenTextFields),
          PrescriptionTextFiled(
            elementList: widget.medicineViewModel.itemMedicineListRoute,
            element: widget.medicineViewModel.itemMedicineListRoute.length == 1 ? route = widget.medicineViewModel.itemMedicineListRoute[0] : route,
            elementError: routeError,
            keyId: 'parameterCode',
            keyName: 'description',
            okFunction: (selectedValue) {
              setState(() {
                route = selectedValue;
                route['isDefault'] = true;
              });
            },
            hintText: TranslationBase.of(context).route,
          ),
          Visibility(
            visible: ProjectViewModel.getVidaPlusStatus() == true,
            child: Column(
              children: [
                SizedBox(height: spaceBetweenTextFields),
                AppTextFieldCustom(
                  hintText: TranslationBase.of(context).duration,
                  validationError: durationError,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly
                  ],
                  enabled: true,
                  inputType: TextInputType.numberWithOptions(decimal: false),
                  onChanged: (value) {
                    if (value == null || value == "") return;

                    if (int.parse(value) < 0) {
                      DrAppToastMsg.showErrorToast(TranslationBase.of(context).durationCannotBeNegative);
                      setState(() {
                        durationError = TranslationBase.of(context).durationCannotBeNegative;
                      });
                      return;
                    }
                    if (int.parse(value) > 365) {
                      DrAppToastMsg.showErrorToast(TranslationBase.of(context).durationCannotBeGreaterThan365);
                      setState(() {
                        durationError = TranslationBase.of(context).durationCannotBeGreaterThan365;
                      });
                      return;
                    }
                    setState(() {
                      duration = value;
                      durationError = null;
                      frequency = null;
                      if (widget.selectedMedication != null && duration != null && frequency != null && strengthController.text != null) {
                        box = widget.medicineViewModel.boxQuintity;
                        return;
                      }
                    });
                  },
                  onFieldSubmitted: () {},
                ),
              ],
            ),
          ),
          SizedBox(height: spaceBetweenTextFields),
          PrescriptionTextFiled(
              hintText: TranslationBase.of(context).frequency,
              elementError: frequencyError,
              // element: frequency,
              element: widget.medicineViewModel.itemMedicineList.length == 1 ? frequency = widget.medicineViewModel.itemMedicineList[0] : frequency,
              elementList: widget.medicineViewModel.itemMedicineList,
              keyId: 'parameterCode',
              keyName: 'description',
              okFunction: (selectedValue) async {
                setState(() {
                  frequency = selectedValue;
                  frequency['isDefault'] = true;
                });
                if (widget.selectedMedication != null && duration != null && frequency != null && strengthController.text != null) {
                  if(ProjectViewModel.getVidaPlusStatus() && units == null){
                    return;
                  }
                  var duration = ProjectViewModel.getVidaPlusStatus() ? int.parse(this.duration) : this.duration['id'];
                  GifLoaderDialogUtils.showMyDialog(context);
                  await widget.medicineViewModel.getBoxQuantity(
                      showLoader: false, freq: frequency['parameterCode'], duration: duration, itemCode: widget.selectedMedication.itemId, strength: double.parse(strengthController.text), unitCode:
                  units['parameterCode']);
                  GifLoaderDialogUtils.hideDialog(context);
                  box = widget.medicineViewModel.boxQuintity;
                  return;
                }
              }),
          SizedBox(height: spaceBetweenTextFields),
          PrescriptionTextFiled(
              hintText: TranslationBase.of(context).doseTime,
              elementError: doseTimeError,
              element: doseTime,
              elementList: widget.medicineViewModel.medicationDoseTimeList,
              keyId: 'id',
              keyName: 'nameEn',
              okFunction: (selectedValue) {
                setState(() {
                  doseTime = selectedValue;
                });
              }),
          SizedBox(height: spaceBetweenTextFields),
          widget.prescriptionViewModel.icd10DeseaseItems.isNotEmpty
              ?
              // PrescriptionTextFiled(
          //     hintText: TranslationBase.of(context).nameOrICD,
          //     elementError: icdCodeError,
          //     element: icdCode,
          //     elementList: widget.prescriptionViewModel.icd10DeseaseItems,
          //     keyId: 'codeId',
          //     keyName: 'asciiDesc',
          //     okFunction: (selectedValue) {
          //       setState(() {
          //         icdCode = selectedValue;
          //       });
          //     })

         Column(
           children:[ InkWell(
               onTap: widget.prescriptionViewModel.icd10DeseaseItems != null
                   ? () {
                 icdCodeList = List.from(widget.prescriptionViewModel.icd10DeseaseItems);
                 setState(() {
                   icdCode = null;
                   icdNameController.text = '';
                 });
               }
                   : null,
               child: AppTextFieldCustom(
                 validationError: icdCodeError,
                 onChanged: (text){
                   icdCodeList = List.from(widget.prescriptionViewModel.icd10DeseaseItems);
                   setState(() {
                     icdNameController.text;
                   });

                 },
                 height: Utils.getTextFieldHeight(),
                 onClick: widget.prescriptionViewModel.icd10DeseaseItems != null
                     ? () {
                   setState(() {
                    icdCode = null;
                     icdNameController.text = '';
                   });
                 }
                     : null,
                 hintText: TranslationBase.of(context).nameOrICD,
                 maxLines: 1,
                 minLines: 1,
                 controller: icdNameController,
                 enabled:true,
                 isTextFieldHasSuffix: true, onFieldSubmitted: () {  },

               )),

             icdCodeList.isNotEmpty  && icdNameController.text.isNotEmpty ?  Container(
                 color: Colors.white,
                 height: MediaQuery.of(context).size.height * 0.4, //height to 9% of screen height,
                 child:ListView.builder(
                   shrinkWrap: true,
                   itemCount:icdCodeList.length,
                   itemBuilder: (context, index) {
                     return InkWell(child:ListTile(
                         title:  AppText( widget.prescriptionViewModel.icd10DeseaseItems[index].asciiDesc + " / " +  widget.prescriptionViewModel.icd10DeseaseItems[index].codeId.toString(), fontSize: 12.0)),
                         onTap: (){
                           icdCode =  widget.prescriptionViewModel.icd10DeseaseItems[index];
                           icdNameController.text =  widget.prescriptionViewModel.icd10DeseaseItems[index].asciiDesc;
                           if(widget.medicineViewModel.patientAssessmentList.isNotEmpty) {
                             widget.medicineViewModel.patientAssessmentList[0].icdCode10ID = widget.prescriptionViewModel.icd10DeseaseItems[index].codeId;
                             widget.medicineViewModel.patientAssessmentList[0].asciiDesc = widget.prescriptionViewModel.icd10DeseaseItems[index].asciiDesc;
                           }
                           icdCodeList.clear();
                           setState(() {

                           });
                         }
                     );

                   },
                 )) :SizedBox()
             ])

           : widget.medicineViewModel.patientAssessmentList.isNotEmpty ?
            Material(
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    Flexible(
                      flex:1,
                      child: AppTextFieldCustom(
                        hintText: "",
                        hideHint: true,
                        controller: TextEditingController( text:widget.medicineViewModel.patientAssessmentList.firstOrNull?.icdCode10ID?.toString()??""),
                        enabled: false,
                        onChanged: (value) {},
                        onFieldSubmitted: () {},
                      ),
                    ),
                    Flexible(flex: 2,
                      child: AppTextFieldCustom(
                        maxLines: 5,
                          hintText:"",
                        hideHint: true,
                        controller: TextEditingController( text:widget.medicineViewModel.patientAssessmentList.firstOrNull?.asciiDesc?.toString()??""),
                        enabled: false,
                        onChanged: (value) {},
                        onFieldSubmitted: () {},
                      ),
                    ),
                  ],
                ),
              ),
            ) :SizedBox(),
          SizedBox(height: spaceBetweenTextFields),
          SizedBox(height: 10,),
          Container(
            color: Colors.transparent,
            child: InkWell(
              onTap: () => selectDate(context, widget.prescriptionViewModel),
              child: AppTextFieldCustom(
                validationError: dateError,
                hintText: TranslationBase.of(context).date,
                isTextFieldHasSuffix: true,
                suffixIcon: IconButton(
                  icon: Icon(
                    Icons.calendar_today,
                    color: Colors.black,
                  ),
                  onPressed: () {},
                ),
                dropDownText: selectedDate != null ? "${AppDateUtils.convertStringToDateFormat(selectedDate.toString(), "yyyy-MM-dd")}" : null,
                enabled: false,
                onChanged: (value) {

                },
                onFieldSubmitted: () {},
              ),
            ),
          ),
          SizedBox(height: spaceBetweenTextFields),
          Visibility(
            visible: ProjectViewModel.getVidaPlusStatus() == false,
            child: Column(
              children: [
                PrescriptionTextFiled(
                  element: duration,
                  elementError: durationError,
                  hintText: TranslationBase.of(context).duration,
                  elementList: widget.medicineViewModel.medicationDurationList,
                  keyName: 'nameEn',
                  keyId: 'id',
                  okFunction: (selectedValue) {
                    setState(() {
                      duration = selectedValue;
                      if (widget.selectedMedication != null && duration != null && frequency != null && strengthController.text != null) {
                        box = widget.medicineViewModel.boxQuintity;
                        return;
                      }
                    });
                  },
                ),
                SizedBox(height: spaceBetweenTextFields),
              ],
            ),
          ),
          Container(
            color: Colors.white,
            child: AppTextFieldCustom(
              hintText: "UOM",
              isTextFieldHasSuffix: false,
              dropDownText: uom != null ? uom : null,
              enabled: false,
              onChanged: (value) {},
              onFieldSubmitted: () {},
            ),
          ),
          SizedBox(height: spaceBetweenTextFields),
          Container(
            color: Colors.white,
            child: AppTextFieldCustom(
              hintText: TranslationBase.of(context).boxQuantity,
              isTextFieldHasSuffix: false,
              dropDownText: box != null ? widget.medicineViewModel.boxQuintity.toString() : null,
              enabled: false,
              onChanged: (value) {},
              onFieldSubmitted: () {},
            ),
          ),
          SizedBox(height: spaceBetweenTextFields),
          Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(6.0)), border: Border.all(width: 1.0, color: HexColor("#CCCCCC"))),
            child: Stack(
              children: [
                TextFields(
                  maxLines: 6,
                  minLines: 4,
                  hintText: TranslationBase.of(context).instruction,
                  controller: instructionController,
                ),
                Positioned(
                  top: 0,
                  right: 15,
                  child: IconButton(
                    icon: Icon(
                      DoctorApp.speechtotext,
                      color: Colors.black,
                      size: 35,
                    ),
                    onPressed: () {
                      initSpeechState().then((value) => {onVoiceText()});
                    },
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: spaceBetweenTextFields),
          Container(
            margin: EdgeInsets.all(SizeConfig.widthMultiplier! * 5),
            child: Wrap(
              alignment: WrapAlignment.center,
              children: <Widget>[
                AppButton(
                  color: Color(0xff359846),
                  title: TranslationBase.of(context).addMedication,
                  fontWeight: FontWeight.w600,
                  onPressed: () async {
                    addMedicationButton(widget.medicineViewModel);
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  selectDate(BuildContext context, PrescriptionViewModel model) async {
    Utils.hideKeyboard(context);
    DateTime selectedDate;
    selectedDate = DateTime.now();
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime.now(),
      lastDate: DateTime(2040),
      initialEntryMode: DatePickerEntryMode.calendar,
    );
    if (picked != null && picked != selectedDate) {
      setState(() {
        this.selectedDate = picked;
      });
    }
  }

  addMedicationButton(MedicineViewModel model) async {
    await locator<AnalyticsService>().logEvent(
      eventCategory: "Add Prescription Form",
      eventAction: "Add Prescription",
    );
    if (duration != null && doseTime != null && frequency != null && selectedDate != null && strengthController.text != "") {
      if (widget.selectedMedication.isNarcotic == true) {
        DrAppToastMsg.showErrorToast(TranslationBase.of(context).narcoticMedicineCanOnlyBePrescribedFromVida);
        Navigator.pop(context);
        return;
      }

      if (double.parse(strengthController.text) > 1000.0) {
        DrAppToastMsg.showErrorToast(TranslationBase.of(context).thousandIsTheMAXForTheStrength);
        return;
      }
      if (double.parse(strengthController.text) < 0.0) {
        DrAppToastMsg.showErrorToast(TranslationBase.of(context).strengthCanNotBeZero);
        return;
      }
      //adding the vida plus validation for duration
      if (ProjectViewModel.getVidaPlusStatus()) {
        if (duration == null) {
          durationError = TranslationBase.of(context).fieldRequired;
          return;
        } else if (int.parse(duration) < 0) {
          setState(() {
            durationError = TranslationBase.of(context).durationCannotBeNegative;
          });
          return;
        } else if (int.parse(duration) > 365) {
          setState(() {
            durationError = TranslationBase.of(context).durationCannotBeGreaterThan365;
          });
          return;
        } else {
          durationError = null;
        }
      }

      if (formKey.currentState!.validate()) {
        Navigator.push(
          context,
          SlideUpPageRoute(
            widget: AddDrugWidget(
              patient: widget.patient,
              medicineModel: widget.medicineViewModel,
              modelPrescription: widget.prescriptionViewModel,
              prescriptionList: widget.prescriptionList,
              route: route,
              doseTime: doseTime,
              duration: duration,
              frequency: frequency,
              units: units,
              uom: uom,
              x: x,
              selectedMedication: widget.selectedMedication,
              strength: strengthController.text,
              indication: indicationController.text,
              instruction: instructionController.text,
              selectedDate: selectedDate,
            ),
          ),
        );
        // Navigator.pop(context);
        // openDrugToDrug(model, prescriptionViewModel);
      }
    } else {
      setState(() {
        if (duration == null) {
          durationError = TranslationBase.of(context).fieldRequired;
        } else {
          durationError = null;
        }
        if (doseTime == null) {
          doseTimeError = TranslationBase.of(context).fieldRequired;
        } else {
          doseTimeError = null;
        }
        if (route == null) {
          routeError = TranslationBase.of(context).fieldRequired;
        } else {
          routeError = null;
        }
        if (frequency == null) {
          frequencyError = TranslationBase.of(context).fieldRequired;
        } else {
          frequencyError = null;
        }
        if (units == null) {
          unitError = TranslationBase.of(context).fieldRequired;
        } else {
          unitError = null;
        }
        if (strengthController.text == "") {
          strengthError = TranslationBase.of(context).fieldRequired;
        } else {
          strengthError = null;
        }

        if (selectedDate == null ) {
          dateError = TranslationBase.of(context).fieldRequired;
        } else {
          dateError = null;
        }

        if ( icdNameController.text == "" && widget.prescriptionViewModel.icd10DeseaseItems.isNotEmpty) {
          icdCodeError = TranslationBase.of(context).fieldRequired;
        } else {
          icdCodeError = null;
        }

      });
    }
    formKey.currentState!.save();
  }
}