import 'package:doctor_app_flutter/config/size_config.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/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.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/network_base_view.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';

import 'ProcedureType.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, this.model, this.patient, @required this.procedureType})
      : super(key: key);

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

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

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

  TextEditingController procedureController = TextEditingController();
  TextEditingController remarksController = TextEditingController();
  List<EntityList> entityList = List();
  List<EntityList> entityListProcedure = List();
  TextEditingController procedureName = TextEditingController();

  dynamic selectedCategory;

  setSelectedType(int 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: Column(
          children: [
            Container(
              height: MediaQuery.of(context).size.height * 0.070,
            ),
            Expanded(
              child: NetworkBaseView(
                baseViewModel: model,
                child: SingleChildScrollView(
                  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,
                                      ),
                                    ),
                                    SizedBox(
                                      width: MediaQuery.of(context).size.width *
                                          0.02,
                                    ),
                                    Expanded(
                                      child: InkWell(
                                        onTap: () {
                                          if (procedureName.text.isNotEmpty &&
                                              procedureName.text.length >= 3)
                                            model.getProcedureCategory(
                                                patientId: patient.patientId,
                                                categoryName:
                                                    procedureName.text);
                                          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,
                                  removeHistory: (item) {
                                    setState(() {
                                      entityList.remove(item);
                                    });
                                  },
                                  addHistory: (history) {
                                    setState(() {
                                      entityList.add(history);
                                    });
                                  },
                                  addSelectedHistories: () {
                                    //TODO build your fun herr
                                    // widget.addSelectedHistories();
                                  },
                                  isEntityListSelected: (master) =>
                                      isEntityListSelected(master),
                                )),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.all(SizeConfig.widthMultiplier * 5),
              child: Wrap(
                alignment: WrapAlignment.center,
                children: <Widget>[
                  AppButton(
                    title: procedureType.getAddButtonTitle(context),
                    fontWeight: FontWeight.w700,
                    color: Color(0xff359846),
                    onPressed: () async {
                      if (entityList.isEmpty == true) {
                        DrAppToastMsg.showErrorToast(
                          TranslationBase.of(context)
                              .fillTheMandatoryProcedureDetails,
                        );
                        return;
                      }

                      await this.model.preparePostProcedure(
                          orderType: selectedType.toString(),
                          entityList: entityList,
                          patient: patient,
                          remarks: remarksController.text);
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  bool isEntityListSelected(EntityList masterKey) {
    Iterable<EntityList> history = entityList
        .where((element) => masterKey.procedureId == element.procedureId);
    if (history.length > 0) {
      return true;
    }
    return false;
  }
}
