import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/model/SOAP/allergy/get_allergies_list_vida_plus.dart';
import 'package:doctor_app_flutter/core/model/SOAP/allergy/get_patient_allergies_list_vida_plus.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.dart';
import 'package:doctor_app_flutter/utils/extenstions_utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.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/rounded_container_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';


class ReactionsSelectionAllergiesWidget extends StatefulWidget {
  final SOAPViewModel? model;
  final AllergiesListVidaPlus? mySelectedAllergy;
  final bool isEdit;
  final PatientAllergiesVidaPlus? editSelectedAllergy;
  final PatiantInformtion patientInfo;
  final String? buttonName;

  ReactionsSelectionAllergiesWidget({
    Key? key,
    required this.model,
    required this.patientInfo,
    this.mySelectedAllergy,
    this.editSelectedAllergy,
    this.isEdit = false,
    this.buttonName,
  }) : super(key: key);

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

class _ReactionsSelectionAllergiesWidgetState
    extends State<ReactionsSelectionAllergiesWidget> {
  bool loading = false;
  TextEditingController remark = TextEditingController();
   List<ExpansionTileController>? controllers =[];

  @override
  void initState() {
    controllers = List.generate(widget.mySelectedAllergy!
        .allergyReactionDTOs!.length, (index) => ExpansionTileController());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        builder: (_, model, w) => AppScaffold(
            isLoading: loading,
            appBar: PatientSearchHeader(
                title: TranslationBase.of(context).selectReaction),
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                widget.mySelectedAllergy != null
                    ? Expanded(
                        child: RoundedContainer(
                            margin: EdgeInsets.only(top:6, left: 15, right: 15, bottom: 6),
                            child: ListView.builder(
                              itemCount: widget.mySelectedAllergy!
                                  .allergyReactionDTOs!.length,
                              itemBuilder: (context, index) {
                                loading = false;

                                return Column(children: [
                                  ExpansionTile(

                                    controller: controllers![index],
                                    key: Key(index.toString()),
                                    // dense: false,
                                    // enableFeedback: false,
                                    // showTrailingIcon: false,
                                    initiallyExpanded: widget
                                        .mySelectedAllergy!
                                        .allergyReactionDTOs![index]
                                        .isSelected!,
                                    leading: Checkbox(
                                        activeColor: Color(0xffD02127),
                                        value: widget
                                            .mySelectedAllergy!
                                            .allergyReactionDTOs![index]
                                            .isSelected!,
                                        onChanged: (value) {
                                          widget
                                              .mySelectedAllergy!
                                              .allergyReactionDTOs![index]
                                              .isSelected = value;

                                          value ==true ?  controllers![index].expand() : controllers![index].collapse() ;
                                         setState(() {

                                         });                                       // setState(() {});
                                        }),
                                    title: AppText(widget
                                        .mySelectedAllergy!
                                        .allergyReactionDTOs![index]
                                        .allergyReactionName!),
                                    children: [
                                      Row(
                                        children: [
                                          Expanded(

                                              child: ListTile(
                                                  contentPadding: EdgeInsets.zero ,

                                                  title: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value: 1,
                                                groupValue: widget
                                                    .mySelectedAllergy!
                                                    .allergyReactionDTOs![index]
                                                    .severity ?? 1,
                                                onChanged: (value) {
                                                  widget
                                                      .mySelectedAllergy!
                                                      .allergyReactionDTOs![
                                                          index]
                                                      .severity = value;
                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .mild,
                                                fontSize: 10,
                                              ),
                                            ],
                                          ))),
                                          Expanded(
                                              child: ListTile(
                                contentPadding: EdgeInsets.zero ,
                                                  title: Row(
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value: 2,
                                                groupValue: widget
                                                    .mySelectedAllergy!
                                                    .allergyReactionDTOs![index]
                                                    .severity,
                                                onChanged: (value) {
                                                  widget
                                                      .mySelectedAllergy!
                                                      .allergyReactionDTOs![
                                                          index]
                                                      .severity = value;
                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .moderate,
                                                fontSize: 10,
                                              ),
                                            ],
                                          ))),
                                          Expanded(
                                              child: ListTile(
                                                  contentPadding: EdgeInsets.zero ,

                                                  title: Row(
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value: 3,
                                                groupValue: widget
                                                    .mySelectedAllergy!
                                                    .allergyReactionDTOs![index]
                                                    .severity,
                                                onChanged: (value) {
                                                  widget
                                                      .mySelectedAllergy!
                                                      .allergyReactionDTOs![
                                                          index]
                                                      .severity = value;
                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .severe,
                                                fontSize: 10,
                                              ),
                                            ],
                                          )))
                                        ],
                                      )
                                    ],
                                  ),
                                  // Divider(),
                                ]);
                              },
                            )))
                    : Expanded(
                        child: RoundedContainer(
                            margin: EdgeInsets.all(15),
                            child: ListView.builder(
                              itemCount: widget.editSelectedAllergy!
                                  .patientsAllergyReactionsDTOs!.length,
                              itemBuilder: (context, index) {
                                loading = false;
                                return Column(children: [
                                  ExpansionTile(
                                    key: Key(index.toString()),
                                    // dense: false,
                                    // enableFeedback: false,
                                    // showTrailingIcon: false,
                                    initiallyExpanded: widget
                                        .editSelectedAllergy!
                                        .patientsAllergyReactionsDTOs![index]
                                        .isSelected!,
                                    leading: Checkbox(
                                        activeColor: Color(0xffD02127),
                                        value: widget
                                            .editSelectedAllergy!
                                            .patientsAllergyReactionsDTOs![
                                                index]
                                            .isSelected!,
                                        onChanged: (value) {
                                          widget
                                              .editSelectedAllergy!
                                              .patientsAllergyReactionsDTOs![
                                                  index]
                                              .isSelected = value;
                                          setState(() {});
                                        }),
                                    title: AppText(widget
                                        .editSelectedAllergy!
                                        .patientsAllergyReactionsDTOs![index]
                                        .allergyReactionName!),
                                    children: [
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Expanded(
                                              child: ListTile(
                                                  contentPadding: EdgeInsets.zero ,

                                                  title: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value:
                                                    TranslationBase.of(context)
                                                        .mild,
                                                groupValue: getSeverityByID(widget
                                                    .editSelectedAllergy!
                                                    .patientsAllergyReactionsDTOs![
                                                        index]
                                                    .severity!),
                                                onChanged: (value) {
                                                  widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .reactionSelection =
                                                      getSeverityByID(widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .severity!);
                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .mild,
                                                fontSize: 10,
                                              ),
                                            ],
                                          ))),
                                          Expanded(
                                              child: ListTile(
                                                  contentPadding: EdgeInsets.zero ,

                                                  title: Row(
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value:
                                                    TranslationBase.of(context)
                                                        .moderate,
                                                groupValue: getSeverityByID(widget
                                                    .editSelectedAllergy!
                                                    .patientsAllergyReactionsDTOs![
                                                        index]
                                                    .severity!),
                                                onChanged: (value) {
                                                  widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .reactionSelection =
                                                      getSeverityByID(widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .severity!);
                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .moderate,
                                                fontSize: 10,
                                              ),
                                            ],
                                          ))),
                                          Expanded(
                                              child: ListTile(
                                                  contentPadding: EdgeInsets.zero ,

                                                  title: Row(
                                            children: <Widget>[
                                              Radio(
                                                activeColor: Color(0xffD02127),
                                                materialTapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                                // Reduces padding around checkbox
                                                visualDensity:
                                                    VisualDensity.compact,
                                                value:
                                                    TranslationBase.of(context)
                                                        .severe,
                                                groupValue: getSeverityByID(widget
                                                    .editSelectedAllergy!
                                                    .patientsAllergyReactionsDTOs![
                                                        index]
                                                    .severity!),
                                                onChanged: (value) {
                                                  widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .reactionSelection =
                                                      getSeverityByID(widget
                                                          .editSelectedAllergy!
                                                          .patientsAllergyReactionsDTOs![
                                                              index]
                                                          .severity!);

                                                  setState(() {});
                                                },
                                              ),
                                              AppText(
                                                TranslationBase.of(context)
                                                    .severe,
                                                fontSize: 10,
                                              ),
                                            ],
                                          )))
                                        ],
                                      )
                                    ],
                                  ),
                                  Divider(),
                                ]);
                              },
                            ))),

              Container(
              margin: EdgeInsets.only(left: 15, right: 15),
                  child:  AppTextFieldCustom(

                  hintText:
                  TranslationBase.of(context).remarks,
                  controller: remark,
                  maxLines: 4,
                  minLines: 4,
                  hasBorder: true,
                  inputType: TextInputType.multiline,

                  onClick: () {},
                  onChanged: (value) {},
                  onFieldSubmitted: () {},
                )),
                SizedBox(height: 90,)
              ],
            ),
            bottomSheet: Container(
                height: 70,
                color: Colors.white,
                margin: EdgeInsets.all(10),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        child: AppButton(
                          title: TranslationBase.of(context).cancel,
                          vPadding: 8,
                          hPadding: 8,
                          color: Color(0xffEAEAEA),
                          fontColor: Colors.black,
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                    Expanded(
                      child: Container(
                        child: AppButton(
                          loading: loading,
                          title: TranslationBase.of(context).save,
                          vPadding: 8,
                          hPadding: 8,
                          color: AppGlobal.appGreenColor,
                          fontColor: Colors.white,
                          onPressed: () {
                            if (widget.isEdit == true) {
                              editAllergy();
                            } else {
                              addAllergy();
                            }
                          },
                        ),
                      ),
                    ),
                  ],
                ))

            // CustomBottomSheetContainer(
            //   buttonColor: Color(0xff359846),
            //   fontColor: Colors.white,
            //   label: TranslationBase.of(context).next,
            //   onTap: () {
            //     widget.addReactionFun(widget
            //         .mySelectedAllergy
            //         );
            //   },
            // )

            ));
  }

  getSeverityByID(int id) {
    Map<int, dynamic> severity = {
      1: TranslationBase.of(context).mild,
      2: TranslationBase.of(context).moderate,
      3: TranslationBase.of(context).severe
    };
    return severity[id];
  }

  addAllergy() async {
    setLoader(true);
    AllergiesListVidaPlus request = widget.mySelectedAllergy!;
    request.remark = remark.text;
    request.allergyReactionDTOs = widget.mySelectedAllergy!.allergyReactionDTOs!
        .where((i) => i.isSelected!)
        .toList();
    await widget.model!.addAllergies(request, widget.patientInfo);
    await widget.model!.getAllergiesVidaPlus(widget.patientInfo);
    setLoader(false);
    Navigator.of(context).pop();
  }

  editAllergy() async{
    setLoader(true);
    PatientAllergiesVidaPlus request = widget.editSelectedAllergy!;
    request.remark = remark.text;
    request.patientsAllergyReactionsDTOs =[];
    widget.mySelectedAllergy!.allergyReactionDTOs!
        .forEach((i){
          if(i.isSelected!){
            request.patientsAllergyReactionsDTOs!.add(PatientsAllergyReactionsDTOs(
                 pomrId: i.pomrid,
                patientID:i.patientID,
                hospitalGroupID:i.hospitalGroupID,
                hospitalID:i.hospitalID,
                isActive:i.isActive,
                allergyReactionMappingID:i.allergyReactionMappingID,
                allergyReactionID:i.allergyReactionID,
                allergyReactionName: i.allergyReactionName,
                severity:i.severity ??1

            ));
          }
        });

    await widget.model!.updateAllergies(request, widget.patientInfo);

    setLoader(false);
    Navigator.of(context).pop();
  }

  setLoader(bool value) {
    loading = value;
    setState(() {});
  }
}
