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/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/core/model/SOAP/selected_items/my_selected_allergy.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/subjective/allergies/reactions_selection.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/subjective/chief_complaint/widgets/add_soap_item.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/widgets/SoapDetailItem.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/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import '../../../../../../core/model/patient/patiant_info_model.dart';
import '../../../../../../widgets/transitions/fade_page.dart';
import 'add_allergies.dart';
import 'package:doctor_app_flutter/core/viewModel/SOAP_view_model.dart';

class UpdateAllergiesWidgetVidaPlus extends StatefulWidget {
  List<PatientAllergiesVidaPlus>? myAllergiesList;
  final PatiantInformtion patientInfo;

  UpdateAllergiesWidgetVidaPlus(
      {Key? key, this.myAllergiesList, required this.patientInfo});

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

bool noKnownAllergies = false;

enum Severity { mild, moderate, severe }

class _UpdateAllergiesWidgetState extends State<UpdateAllergiesWidgetVidaPlus> {
  SOAPViewModel? model;

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model) {},
        builder: (_, model, w) => Column(
              children: [
                SizedBox(
                  height: 20,
                ),
                AddSoapItem(
                  title: "${TranslationBase.of(context).addAllergies}",
                  onAddSoapItemClicked: () {
                    Navigator.push(
                      context,
                      FadePage(
                        page: AddAllergies(
                          patientInfo: widget.patientInfo,
                          // addAllergiesFun: (){
                          //   print("addAllergies save");
                          // },
                        ),
                      ),
                    );
                  },
                ),
                SizedBox(
                  height: 20,
                ),
                widget.myAllergiesList!.isEmpty
                    ? Row(
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          Checkbox(
                            value: noKnownAllergies,
                            checkColor: Colors.white,
                            activeColor: Colors.red,
                            onChanged: (value) {
                              noKnownAllergies = value!;
                             if(value){
                               setNoKnownAllergy(model);
                             }
                              setState(() {

                              });
                            },
                            materialTapTargetSize:
                                MaterialTapTargetSize.shrinkWrap,
                            // Reduces padding around checkbox
                            visualDensity:
                                VisualDensity.compact, // Minimizes size further
                          ),
                          AppText(TranslationBase.of(context).noKnownAllergies)
                        ],
                      )
                    : Divider(
                        thickness: 1,
                        color: Color(0xffEFEFEF),
                      ),
                ListView(
                    padding: EdgeInsets.all(10),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    children: widget.myAllergiesList!.map((selectedAllergy) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: AppText(
                                  selectedAllergy.allergyName!,
                                  fontSize: 12,
                                  fontWeight: FontWeight.w800,
                                  letterSpacing: -0.48,
                                ),
                              ),
                              SizedBox(
                                width: 8,
                              ),
                              Status(
                                status: (selectedAllergy.isActivePatientsAllergy == true ) ? TranslationBase.of(context).active : TranslationBase.of(context).resolved,
                              )
                            ],
                          ),
                          selectedAllergy.patientsAllergyReactionsDTOs!
                                      .isNotEmpty &&
                                  selectedAllergy.isActivePatientsAllergy!
                              ? ListView(
                                  shrinkWrap: true,
                                  children: selectedAllergy
                                      .patientsAllergyReactionsDTOs!
                                      .map((PatientsAllergyReactionsDTOs
                                              reaction) =>
                                          Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              SizedBox(
                                                height: 5,
                                              ),
                                              Row(
                                                children: [
                                                  AppText(
                                                    reaction
                                                        .allergyReactionName!,
                                                    fontSize: 10,
                                                  ),
                                                  AppText(" - "),
                                                  AppText(
                                                    Severity
                                                        .values[
                                                            reaction.severity! -
                                                                1]
                                                        .name,
                                                    color: getColor(
                                                        reaction.severity!),
                                                    fontSize: 10,
                                                    fontWeight: FontWeight.w600,
                                                    letterSpacing: -0.48,
                                                  )
                                                ],
                                              )
                                            ],
                                          ))
                                      .toList())
                              : selectedAllergy.isActivePatientsAllergy!
                                  ? AppText("----")
                                  : AppText(
                                      TranslationBase.of(context).resolved,
                                      color: Colors.lightBlue,
                                      fontSize: 10,
                                      fontWeight: FontWeight.w600,
                                      letterSpacing: -0.48,
                                    ),
                          selectedAllergy.isActivePatientsAllergy! &&
                                  selectedAllergy.allergyID! != 0
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    TextButton.icon(
                                      onPressed: () {
                                        editAllergy(selectedAllergy, model);
                                      },
                                      icon: SvgPicture.asset(
                                        "assets/images/svgs/edit-icon.svg",
                                        height: 16,
                                      ),
                                      label: AppText(
                                        TranslationBase.of(context).edit,
                                        fontSize: 12,
                                      ),
                                    ),
                                    TextButton.icon(
                                        onPressed: () {
                                          resolveAllergy(
                                              model, selectedAllergy);
                                        },
                                        icon: SvgPicture.asset(
                                          "assets/images/svgs/resolve.svg",
                                          height: 18,
                                        ),
                                        label: AppText(
                                            TranslationBase.of(context).resolve,
                                            fontSize: 12,
                                            color: Color(0xff359846)))
                                  ],
                                )
                              : selectedAllergy.allergyID! != 0
                                  ? Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        TextButton.icon(
                                            onPressed: () {
                                              activateAllergy(
                                                  model, selectedAllergy);
                                            },
                                            icon: SvgPicture.asset(
                                              "assets/images/svgs/resolve.svg",
                                              height: 18,
                                              color: Color(0xffD02127),
                                            ),
                                            label: AppText(
                                                TranslationBase.of(context)
                                                    .activate,
                                                fontSize: 12,
                                                color: Color(0xffD02127)))
                                      ],
                                    )
                                  : SizedBox()
                        ],
                      );
                    }).toList()),
              ],
            ));
  }

  resolveAllergy(
      SOAPViewModel model, PatientAllergiesVidaPlus selectedAllergy) async {
    GifLoaderDialogUtils.showMyDialog(context);

    await model.resolveAllergies(selectedAllergy, widget.patientInfo);
    await model.getAllergiesVidaPlus(widget.patientInfo);
    GifLoaderDialogUtils.hideDialog(context);
  }

  activateAllergy(
      SOAPViewModel model, PatientAllergiesVidaPlus selectedAllergy) async {
    GifLoaderDialogUtils.showMyDialog(context);

    await model.updateAllergies(selectedAllergy, widget.patientInfo);
    await model.getAllergiesVidaPlus(widget.patientInfo);
    GifLoaderDialogUtils.hideDialog(context);
  }

  Color getColor(int severity) {
    Map<int, dynamic> color = {
      1: Color(0xff359846),
      2: Color(0xFFCC9B14),
      3: Color(0xffD02127)
    };
    return color[severity];
  }

  editAllergy(
      PatientAllergiesVidaPlus selectedAllergy, SOAPViewModel model) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await model.getEditAllergiesVidaPlus(selectedAllergy.allergyID!);
    GifLoaderDialogUtils.hideDialog(context);
    markSelected(selectedAllergy, model);
    Navigator.push(
        context,
        FadePage(
            page: ReactionsSelectionAllergiesWidget(
          model: model,
          mySelectedAllergy: model.searchAllergiesVidaPlus[0],
          editSelectedAllergy: selectedAllergy!,
          patientInfo: widget.patientInfo,
              isEdit: true,
        )));
  }

  markSelected(PatientAllergiesVidaPlus selectedAllergy, SOAPViewModel model) {
    model.searchAllergiesVidaPlus[0].allergyReactionDTOs!.forEach((element) {
      selectedAllergy.patientsAllergyReactionsDTOs!.forEach((element2) {
        if (element.allergyReactionID == element2.allergyReactionID) {
          element.isSelected = true;
          element.severity =element2.severity;
        }
      });
    });
  }

  setNoKnownAllergy(SOAPViewModel model) async {
    GifLoaderDialogUtils.showMyDialog(context);
    AllergiesListVidaPlus  request= AllergiesListVidaPlus();


    await model!.addAllergies(request, widget.patientInfo, isNoKnown: true);
    await model!.getAllergiesVidaPlus(widget.patientInfo);
    setState(() {

    });
    GifLoaderDialogUtils.hideDialog(context);
  }
}
