import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/model/procedure/categories_procedure.dart';
import 'package:doctor_app_flutter/core/viewModel/procedure_View_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/procedures/procedure_type.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/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/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';

import '../../widgets/dialog/confirm_dialog.dart';
import '../../widgets/transitions/slide_up_page.dart';
import 'entity_list_checkbox_search_widget.dart';

class AddProcedurePage extends StatefulWidget {
  final ProcedureViewModel model;
  final PatiantInformtion patient;
  final ProcedureType procedureType;

  const AddProcedurePage({Key? key, required this.model, required this.patient, required this.procedureType}) : super(key: key);

  @override
  _AddProcedurePageState createState() => _AddProcedurePageState(patient: patient, model: model, procedureType: this.procedureType);
}

class _AddProcedurePageState extends State<AddProcedurePage> {
  String? selectedType;
  ProcedureViewModel model;
  PatiantInformtion patient;
  ProcedureType procedureType;

  _AddProcedurePageState({required this.patient, required this.model, required this.procedureType});

  TextEditingController procedureController = TextEditingController();
  TextEditingController remarksController = TextEditingController();
  List<EntityList> entityList = [];

  List<EntityList> entityListProcedure = [];
  TextEditingController procedureName = TextEditingController();

  dynamic selectedCategory;

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

  @override
  Widget build(BuildContext context) {
    return BaseView<ProcedureViewModel>(
      onModelReady: (model) {
        model.getProcedureCategory(categoryName: procedureType.getCategoryName(), categoryID: procedureType.getCategoryId(), patientId: patient.patientId);
      },
      builder: (BuildContext context, ProcedureViewModel model, Widget? child) => AppScaffold(
        isShowAppBar: false,
        body: NetworkBaseView(
          baseViewModel: model,
          child: SingleChildScrollView(
            child: FractionallySizedBox(
              widthFactor: .97,
              child: Center(
                child: Column(
                  children: [
                    Container(
                      height: MediaQuery.of(context).size.height * 0.070,
                    ),
                    // NetworkBaseView(
                    //   baseViewModel: model,
                    //   child:
                      Container(
                        child: Padding(
                          padding: EdgeInsets.all(12.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              if (procedureType == ProcedureType.PROCEDURE)
                                Column(
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        AppText(
                                          TranslationBase.of(context).pleaseEnterProcedure,
                                          fontWeight: FontWeight.w700,
                                          fontSize: 20,
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      height: MediaQuery.of(context).size.height * 0.02,
                                    ),
                                    Row(
                                      children: [
                                        Container(
                                          width: MediaQuery.of(context).size.width * 0.79,
                                          child: AppTextFieldCustom(
                                            hintText: TranslationBase.of(context).searchProcedureHere,
                                            isTextFieldHasSuffix: false,
                                            maxLines: 1,
                                            minLines: 1,
                                            hasBorder: true,
                                            controller: procedureName,
                                            onChanged: (value) {},
                                            onFieldSubmitted: () {},
                                          ),
                                        ),
                                        SizedBox(
                                          width: MediaQuery.of(context).size.width * 0.02,
                                        ),
                                        Expanded(
                                          child: InkWell(
                                            onTap: () async {
                                              if (procedureName.text.isNotEmpty && procedureName.text.length >= 3) {
                                                GifLoaderDialogUtils.showMyDialog(context);
                                                await model.getProcedureCategory(patientId: patient.patientId, categoryName: procedureName.text, isLocalBusy: true);
                                                if (model.state == ViewState.ErrorLocal) {
                                                  DrAppToastMsg.showErrorToast(model.error);
                                                }
                                                GifLoaderDialogUtils.hideDialog(context);
                                              } else {
                                                DrAppToastMsg.showErrorToast(
                                                  TranslationBase.of(context).atLeastThreeCharacters,
                                                );
                                              }
                                            },
                                            child: Icon(
                                              Icons.search,
                                              size: 25.0,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              if ((procedureType == ProcedureType.PROCEDURE ? procedureName.text.isNotEmpty : true) && model.categoriesList.length != 0)
                                // NetworkBaseView(
                                //     baseViewModel: model,
                                //     child:
                                    EntityListCheckboxSearchWidget(
                                      model: widget.model,
                                      masterList: model.categoriesList[0].entityList!,
                                      shouldDisplaySearchField: procedureType != ProcedureType.PROCEDURE ,
                                      removeProcedure: (item) {
                                  EntityList? itemToBeRemoved = entityList.firstWhere((element) => item.procedureId == element.procedureId, orElse: () => EntityList());
                                  if (itemToBeRemoved.procedureId != null) {
                                    setState(() {
                                      entityList.remove(itemToBeRemoved);
                                    });
                                  }
                                },
                                addProcedure: (history) {
                                        setState(() {
                                          entityList.add(history);
                                        });
                                      },
                                      addSelectedHistories: () {},
                                      selectedType: (val) {
                                        selectedType = val;
                                      },
                                      isEntityListSelected: (master) => widget.model.isEntityListSelected(master, entityList),
                                    ),
      // ),
                              SizedBox(
                                height: 10,
                              )
                            ],
                          ),
                        ),
                      ),
                    // ),
                  ],
                ),
              ),
            ),
          ),
        ),
        bottomSheet: model.state == ViewState.BusyLocal || entityList.isEmpty
            ? Container(
                height: 0,
              )
            : CustomBottomSheetContainer(
                label: procedureType.getAddButtonTitle(context),
                onTap: () async {

                    if (entityList.isEmpty == true) {

                      DrAppToastMsg.showErrorToast(
                        TranslationBase.of(context).fillTheMandatoryProcedureDetails,
                      );
                      GifLoaderDialogUtils.hideDialog(context);
                      return;
                    }
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return ConfirmationDialog(title:TranslationBase.of(context).afterOrderCreation,
                            onTapGrant: () async{
                              // GifLoaderDialogUtils.showMyDialog(context);
                              await widget.model.preparePostProcedure(
                                orderType: selectedType.toString(),
                                entityList: entityList,
                                patient: patient,
                                remarks: remarksController.text,
                                procedureType: ProcedureType.PROCEDURE,
                                isLocalBusy: false,
                              );
                              // GifLoaderDialogUtils.hideDialog(context);
                            });

                      },
                    );


                }),
      ),
    );
  }
}
