import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:doctor_app_flutter/core/enum/master_lookup_key.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/SOAP/my_selected_allergy.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/util/helpers.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/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/master_key_checkbox_search_allergies_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/network_base_view.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../../shared_soap_widgets/bottom_sheet_title.dart';

class AddAllergies extends StatefulWidget {
  final Function addAllergiesFun;
  final List<MySelectedAllergy> myAllergiesList;

  const AddAllergies({Key key, this.addAllergiesFun, this.myAllergiesList})
      : super(key: key);

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

class _AddAllergiesState extends State<AddAllergies> {
  List<MasterKeyModel> allergiesList;
  List<MasterKeyModel> allergySeverityList;
  TextEditingController remarkController = TextEditingController();
  TextEditingController severityController = TextEditingController();
  TextEditingController allergyController = TextEditingController();
  List<MySelectedAllergy> myAllergiesListLocal;

  @override
  initState() {
    super.initState();
    myAllergiesListLocal = [...widget.myAllergiesList];
  }

  GlobalKey key = new GlobalKey<AutoCompleteTextFieldState<MasterKeyModel>>();
  bool isFormSubmitted = false;

  InputDecoration textFieldSelectorDecoration(
      String hintText, String selectedText, bool isDropDown,
      {IconData icon}) {
    return InputDecoration(
      contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Colors.grey, width: 1.0),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Colors.grey, width: 1.0),
        borderRadius: BorderRadius.circular(8),
      ),
      disabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Colors.grey, width: 1.0),
        borderRadius: BorderRadius.circular(8),
      ),
      hintText: selectedText != null ? selectedText : hintText,
      suffixIcon: isDropDown ? Icon(icon ?? Icons.arrow_drop_down) : null,
      hintStyle: TextStyle(
          fontSize: 10,
          color: Theme.of(context).hintColor,
          fontWeight: FontWeight.w700),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
      heightFactor: 1,
      child: BaseView<SOAPViewModel>(
        onModelReady: (model) async {
          if (model.allergiesList.length == 0) {
            await model.getMasterLookup(MasterKeysService.Allergies);
          }
          if (model.allergySeverityList.length == 0) {
            await model.getMasterLookup(MasterKeysService.AllergySeverity);
          }
        },
        builder: (_, model, w) => AppScaffold(
            baseViewModel: model,
            isShowAppBar: false,
            body: Center(
              child: Container(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      BottomSheetTitle(
                        title: TranslationBase.of(context).addAllergies,
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      SizedBox(
                        height: 16,
                      ),
                      Expanded(
                        child: Center(
                          child: FractionallySizedBox(
                            widthFactor: 0.9,
                            child: Center(
                              child: NetworkBaseView(
                                baseViewModel: model,
                                child: MasterKeyCheckboxSearchAllergiesWidget(
                                  model: model,
                                  masterList: model.allergiesList,
                                  removeAllergy: (master) {
                                    setState(() {
                                      removeAllergyFromLocalList(master);
                                    });
                                  },
                                  addAllergy:
                                      (MySelectedAllergy mySelectedAllergy) {
                                    addAllergyLocally(mySelectedAllergy);
                                },
                                  addSelectedAllergy: () => widget
                                      .addAllergiesFun(myAllergiesListLocal),
                                  isServiceSelected: (master) =>
                                      isServiceSelected(master),
                                  getServiceSelectedAllergy: (master) =>
                                      getSelectedAllergy(master),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.11,
                      ),
                    ]),
              ),
            ),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(
                      title:
                      TranslationBase.of(context).addAllergies,
                      padding: 10,
                      color: Color(0xFF359846),
                      onPressed: () {
                        widget.addAllergiesFun(myAllergiesListLocal);
                      },
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 5,
              ),
            ],
          ),
        ),),
      ),
    );
  }

  isServiceSelected(MasterKeyModel masterKey) {
    Iterable<MySelectedAllergy> allergy = myAllergiesListLocal.where(
        (element) =>
            masterKey.id == element.selectedAllergy.id &&
            masterKey.typeId == element.selectedAllergy.typeId &&
            element.isChecked);
    if (allergy.length > 0) {
      return true;
    }
    return false;
  }

  removeAllergyFromLocalList(MasterKeyModel masterKey) {
    myAllergiesListLocal
        .removeWhere((element) => element.selectedAllergy.id == masterKey.id);
  }

  MySelectedAllergy getSelectedAllergy(MasterKeyModel masterKey) {
    Iterable<MySelectedAllergy> allergy = myAllergiesListLocal.where(
        (element) =>
            masterKey.id == element.selectedAllergy.id &&
            masterKey.typeId == element.selectedAllergy.typeId &&
            element.isChecked);
    if (allergy.length > 0) {
      return allergy.first;
    }
    return null;
  }

  addAllergyLocally(MySelectedAllergy mySelectedAllergy) {
    if (mySelectedAllergy.selectedAllergy == null) {
      Helpers.showErrorToast(TranslationBase
          .of(context)
          .requiredMsg);
    } else {
      setState(() {
        List<MySelectedAllergy> allergy =
        // ignore: missing_return
        myAllergiesListLocal
            .where((element) =>
        mySelectedAllergy.selectedAllergy.id ==
            element.selectedAllergy.id)
                .toList();

        if (allergy.isEmpty) {
          myAllergiesListLocal.add(mySelectedAllergy);
        } else {
          allergy.first.selectedAllergy = mySelectedAllergy.selectedAllergy;
          allergy.first.selectedAllergySeverity =
              mySelectedAllergy.selectedAllergySeverity;
          allergy.first.remark = mySelectedAllergy.remark;
          allergy.first.isChecked = mySelectedAllergy.isChecked;
        }
      });
    }
  }
}
