// ignore: must_be_immutable
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/SOAP/home_medication_vp/GetSearchCurrentMedication.dart';
import 'package:doctor_app_flutter/core/model/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_allergy.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/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/medicine/medicine_search_screen.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/objective/widget/EmptyExamination.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/subjective/medication/dropdown_popup.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/bottom_sheet/custom_bottom_sheet_container.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/dialogs/master_key_dailog.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/rounded_container_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/auto_complete_text_field.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/text_fields_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

// ignore: must_be_immutable
class AddMedication extends StatefulWidget {
  final Function() addMedicationFun;
  final PatiantInformtion? patientInfo;
  AddMedication({Key? key, required this.addMedicationFun, this.patientInfo}) : super(key: key);

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

class _AddMedicationState extends State<AddMedication> {
  int? _selectedMedicationStrength;
  int? _selectedMedicationRoute;
  int? _selectedMedicationFrequency;
  TextEditingController medicationController = TextEditingController();

  TextEditingController doseController = TextEditingController();
  TextEditingController strengthController = TextEditingController();
  TextEditingController routeController = TextEditingController();
  TextEditingController frequencyController = TextEditingController();
  GetSearchCurrentMedication? _selectedMedication;
  TextEditingController remark = TextEditingController();
  bool isVisible = false;
  GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>> key =
      GlobalKey<AutoCompleteTextFieldState<GetMedicationResponseModel>>();
  bool isFormSubmitted = false;

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<SOAPViewModel>(
      onModelReady: (model) async {
        // model.onAddMedicationStart();
      },
      builder: (_, model, w) => AppScaffold(
          backgroundColor: Colors.white,
          baseViewModel: model,
          isShowAppBar: true,
          appBar: PatientSearchHeader(
            title: TranslationBase.of(context).addMedication,
          ),
          body: Container(
            padding: EdgeInsets.all(15),
            child: SingleChildScrollView(
              child: Column(
                children: [

                  AppTextFieldCustom(
                    height: Utils.getTextFieldHeight(),
                    controller: medicationController,
                    hintText:
                        TranslationBase.of(context).searchMedicineNameHere,
                    minLines: 1,
                    maxLines: 1,
                    isTextFieldHasSuffix: true,
                    validationError: isFormSubmitted && medicationController.text.isEmpty  ? TranslationBase.of(context).emptyMessage : null,
                    suffixIcon: IconButton(
                      icon: model.state == ViewState.BusyLocal
                          ? SizedBox(
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                              ),
                              height: 10,
                              width: 10,
                            )
                          : Icon(
                              Icons.search,
                              color: Colors.grey.shade600,
                            ),
                      onPressed: () {
                        searchMedication(model);
                      },
                    ),
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  ),
                  // ),
                  // ),
                  model.getMedicationListVP!.isNotEmpty & isVisible
                      ? RoundedContainer(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height * 0.60,
                          child: model.state == ViewState.Idle
                              ? ListView.builder(
                                  itemCount: model.getMedicationListVP!.length,
                                  itemBuilder: (context, index) {
                                    return ListTile(
                                        onTap: () {
                                          selectMedication(model, index);
                                        },
                                        title: AppText(
                                          model.getMedicationListVP![index]
                                              .formularyName!,
                                        ));
                                  },
                                )
                              : SizedBox())
                      : SizedBox(),

                  if (_selectedMedication != null)
                    Column(
                      children: [
                        SizedBox(
                          height: 3,
                        ),
                        Container(
                          width: MediaQuery.of(context).size.width * 0.9,
                          child: AppText(
                            _selectedMedication!.formularyName!,
                            color: Color(0xFF575757),
                            fontSize: 10,
                            fontWeight: FontWeight.w700,
                            letterSpacing: -0.4,
                          ),
                        ),
                      ],
                    ),
                  SizedBox(
                    height: 5,
                  ),

                  SizedBox(
                    height: 5,
                  ),
                  AppTextFieldCustom(
                    height: Utils.getTextFieldHeight(),
                    enabled: true,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    // onClick: model.medicationDoseTimeList != null
                    //     ? () {
                    //   MasterKeyDailog dialog = MasterKeyDailog(
                    //     list: model.medicationDoseTimeList,
                    //     okText: TranslationBase.of(context).ok,
                    //     // selectedValue: _selectedMedicationDose,
                    //     okFunction: (selectedValue) {
                    //       setState(() {
                    //         _selectedMedicationDose = selectedValue;
                    //
                    //         doseController.text = projectViewModel.isArabic ? _selectedMedicationDose!.nameAr! : _selectedMedicationDose!.nameEn!;
                    //       });
                    //     },
                    //   );
                    //   showDialog(
                    //     barrierDismissible: false,
                    //     context: context,
                    //     builder: (BuildContext context) {
                    //       return dialog;
                    //     },
                    //   );
                    // }
                    //     : null,
                    hintText: TranslationBase.of(context).doseDetails,
                    maxLines: 1,
                    minLines: 1,

                    isTextFieldHasSuffix: false,
                    controller: doseController,
                    validationError: isFormSubmitted && doseController.text.isEmpty  ? TranslationBase.of(context).emptyMessage : null,
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  AppTextFieldCustom(
                    height: Utils.getTextFieldHeight(),
                    enabled: false,
                    isTextFieldHasSuffix: true,
                    onClick: model.getSearchCurrentMedicationDetails!
                                .isNotEmpty &&
                            model.getSearchCurrentMedicationDetails![0]
                                    .itemStrengthDetailsDto !=
                                null
                        ? () {

                            DropdownPopup dialog = DropdownPopup(
                              medicationDetails:
                                  model.getSearchCurrentMedicationDetails![0],
                              isStrength: true,
                              okText: TranslationBase.of(context).ok,
                              selectedID:model.getSearchCurrentMedicationDetails![0]
                                  .itemStrengthDetailsDto![0]
                                  .strengthId!,
                              okFunction: (int id, String value) {
                                _selectedMedicationStrength = id;
                                strengthController.text = value;
                                setState(() {});
                              },
                            );
                            showDialog(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) {
                                return dialog;
                              },
                            );
                          }
                        : null,
                    hintText: TranslationBase.of(context).strength,
                    maxLines: 1,
                    minLines: 1,
                    controller: strengthController,
                    // validationError: isFormSubmitted && _selectedMedicationStrength == null ? TranslationBase.of(context).emptyMessage : null,
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  SizedBox(
                    height: 5,
                  ),

                  AppTextFieldCustom(
                    height: Utils.getTextFieldHeight(),
                    enabled: false,
                    isTextFieldHasSuffix: true,

                    onClick: model.getSearchCurrentMedicationDetails!
                                .isNotEmpty &&
                            model.getSearchCurrentMedicationDetails![0]
                                    .genericItemRouteDetailsEntity !=
                                null
                        ? () {

                            DropdownPopup dialog = DropdownPopup(
                              medicationDetails:
                                  model.getSearchCurrentMedicationDetails![0],
                              okText: TranslationBase.of(context).ok,
                              isRoute: true,
                              selectedID: model
                                  .getSearchCurrentMedicationDetails![0]
                                  .genericItemRouteDetailsEntity![0]
                                  .routeId!,
                              // selectedText: ,
                              okFunction: (int id, String value) {
                                setState(() {
                                  _selectedMedicationRoute = id;
                                  routeController.text = value;
                                });
                              },
                            );
                            showDialog(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) {
                                return dialog;
                              },
                            );
                          }
                        : null,
                    hintText: TranslationBase.of(context).route,
                    maxLines: 1,
                    minLines: 1,
                    controller: routeController,
                    // validationError: isFormSubmitted && _selectedMedicationRoute == null ? TranslationBase.of(context).emptyMessage : null,
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  ),
                  SizedBox(
                    height: 10,
                  ),

                  AppTextFieldCustom(
                    height: Utils.getTextFieldHeight(),

                    onClick: model.getSearchCurrentMedicationDetails!
                                .isNotEmpty &&
                            model.getSearchCurrentMedicationDetails![0]
                                    .genericItemFrequencyDetailsEntity !=
                                null
                        ? () {

                            DropdownPopup dialog = DropdownPopup(
                              medicationDetails:
                                  model.getSearchCurrentMedicationDetails![0],
                              okText: TranslationBase.of(context).ok,
                              selectedID: model
                                  .getSearchCurrentMedicationDetails![0]
                                  .genericItemFrequencyDetailsEntity![0]
                                  .frequencyId! ,
                              okFunction: (int id, String value) {
                                _selectedMedicationFrequency = id;
                                frequencyController.text = value;
                                setState(() {});
                              },
                            );
                            showDialog(
                              barrierDismissible: false,
                              context: context,
                              builder: (BuildContext context) {
                                return dialog;
                              },
                            );
                          }
                        : null,
                    hintText: TranslationBase.of(context).frequency,
                    enabled: false,
                    maxLines: 1,
                    minLines: 1,
                    isTextFieldHasSuffix: true,
                    controller: frequencyController,

                    // validationError: isFormSubmitted && _selectedMedicationFrequency == null ? TranslationBase.of(context).emptyMessage : null,
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  AppTextFieldCustom(
                    hintText: TranslationBase.of(context).remarks,
                    controller: remark,
                    maxLines: 4,
                    minLines: 4,
                    hasBorder: true,
                    inputType: TextInputType.multiline,
                    onClick: () {},
                    onChanged: (value) {},
                    onFieldSubmitted: () {},
                  )
                ],
              ),
            ),
          ),
          bottomSheet:
               CustomBottomSheetContainer(
                  label: TranslationBase.of(context).addMedication,
                  onTap: () {
                    if(medicationController.text.isNotEmpty &&  doseController.text.isNotEmpty){
                      addMedication(model);
                    }else {
                      isFormSubmitted = true;
                      setState(() {

                      });
                    }
                  },
                )),
    );
  }

  searchMedication(model) async {
    await model.searchCurrentMedication(medicationController.text);
    isVisible = true;
    setState(() {});
  }

  selectMedication(SOAPViewModel model, int index) {
    _selectedMedication = model.getMedicationListVP![index];
    medicationController.text =
        model.getMedicationListVP![index].formularyName!;
    isVisible = false;
    getOtherDetails(model, model.getMedicationListVP![index]);
    setState(() {});
  }

  getOtherDetails(
      SOAPViewModel model, GetSearchCurrentMedication selectMedicine) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.getCurrentMedicationDetails(selectMedicine.genericFormularyId!);

    GifLoaderDialogUtils.hideDialog(context);
    setDefaultValues(model);
  }
  setDefaultValues(SOAPViewModel model){
    _selectedMedicationStrength =  model.getSearchCurrentMedicationDetails![0]
        .itemStrengthDetailsDto![0]
        .strengthId!;
    strengthController.text =  model
        .getSearchCurrentMedicationDetails![0]
        .itemStrengthDetailsDto![0]
        .strength!;

    _selectedMedicationRoute = model
        .getSearchCurrentMedicationDetails![0]
        .genericItemRouteDetailsEntity![0]
        .routeId!;
    routeController.text= model
        .getSearchCurrentMedicationDetails![0]
        .genericItemRouteDetailsEntity![0]
        .route!;
    _selectedMedicationFrequency = model
        .getSearchCurrentMedicationDetails![0]
        .genericItemFrequencyDetailsEntity![0]
        .frequencyId!;
    frequencyController.text= model
        .getSearchCurrentMedicationDetails![0]
        .genericItemFrequencyDetailsEntity![0]
        .frequency!;

  }

  addMedication(SOAPViewModel model) async{
    Map<String, dynamic> request ={

    "doseQuantity": doseController.text,
    "frequencyId": _selectedMedicationFrequency,
    "frequencyString":frequencyController.text,
    "strengthId": _selectedMedicationStrength,
    "strengthString": strengthController.text,
    "routeId": _selectedMedicationRoute,
    "routeString": routeController.text,
    "remarks": remark.text,
    "sentence": medicationController.text,
    "formularyName": _selectedMedication!.formularyName!,
    "genericFormularyId": _selectedMedication!.genericFormularyId!,

  };
    GifLoaderDialogUtils.showMyDialog(context);

    await model.addCurrentMedication(request, widget.patientInfo!);
    await model.getHomeMedication(widget.patientInfo!);
    GifLoaderDialogUtils.hideDialog(context);
    Navigator.of(context).pop();

  }
}
