import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/audit_diagnosis.dart';
import 'package:doctor_app_flutter/core/model/SOAP/assessment/patient_previous_diagnosis.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/profile/soap_update_vida_plus/assessment/add_diagnosis.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/assessment/widget/audit_list_bottom_sheet.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/assessment/widget/edit_diagnosis.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update_vida_plus/assessment/widget/empty_diagnosis.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/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';

import '../../../../../../widgets/shared/text_fields/app-textfield-custom.dart';

class CurrentDiagnosis extends StatefulWidget {
  final PatiantInformtion patientInfo;
  final List<PatientPreviousDiagnosis> currentDiagnosisItems;
  final SOAPViewModel model;

  const CurrentDiagnosis(
      {super.key,
      required this.currentDiagnosisItems,
      required this.patientInfo,
      required this.model});

  @override
  State<CurrentDiagnosis> createState() => _CurrentDiagnosisState();
}

class _CurrentDiagnosisState extends State<CurrentDiagnosis> {
  TextEditingController deleteController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return BaseView<SOAPViewModel>(
        onModelReady: (model) async {},
        builder: (_, model, w) {
          if (model.showAudit) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              showAuditBottomSheet(context, model.auditDiagnosislist,
                  model.toggleShowBottomSheetValue);
              model.toggleShowBottomSheetValue(false);
            });
          }

          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedBox(
                  height: 10,
                ),
                AddSoapItem(
                    title: TranslationBase.of(context).addNewDiagnosis,
                    onAddSoapItemClicked: () async {
                      bool result = await Navigator.push(
                          context,
                          FadePage(
                              page: AddDiagnosis(
                            patientInfo: widget.patientInfo,
                          )));
                      if (result) {
                        model.getCurrentDiagnosisList(widget.patientInfo);
                      }
                    }),
                SizedBox(
                  height: 16,
                ),
                Divider(),
                SizedBox(
                  height: 16,
                ),
                if (widget.currentDiagnosisItems.isEmpty) ...{
                  Center(
                    child: EmptyDiagnosis(),
                  ),
                } else ...{
                  Flexible(
                      child: ListView.separated(
                          itemBuilder: (_, index) {
                            return SoapDetailItem(
                              title: widget.currentDiagnosisItems[index]
                                      .selectedDisease ??
                                  '',
                              status:
                                  widget.currentDiagnosisItems[index].status ??
                                      '',
                              condition: model.getConditionValue(widget
                                          .currentDiagnosisItems[index]
                                          .condition ??
                                      '') ??
                                  '',
                              type: model.getDiagnosisTypeValue(widget
                                          .currentDiagnosisItems[index]
                                          .diagnosisType ??
                                      '') ??
                                  '',
                              remarks:
                                  widget.currentDiagnosisItems[index].remarks ??
                                      '',
                              onSoapDetailActionClicked: (action) async {
                                switch (action) {
                                  case SoapDetailItemActions.AUDIT:
                                    model.getAuditOfDiagnosis(
                                        widget.patientInfo,
                                        widget.currentDiagnosisItems[index]
                                                .patientProblemRevisionId
                                                ?.toString() ??
                                            '');
                                    break;
                                  case SoapDetailItemActions.EDIT:
                                    if (widget.currentDiagnosisItems[index]
                                            .status ==
                                        "Deleted") {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyDeleted);
                                      return;
                                    }

                                    if (widget.currentDiagnosisItems[index]
                                            .resolved ==
                                        true) {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyResolved);
                                      return;
                                    }

                                    bool result = await Navigator.push(
                                        context,
                                        FadePage(
                                            page: EditDiagnosis(
                                          patientInfo: widget.patientInfo,
                                          diagnosis: widget
                                              .currentDiagnosisItems[index],
                                        )));
                                    if (result) {
                                      model.getCurrentDiagnosisList(
                                          widget.patientInfo);
                                    }
                                    break;
                                  case SoapDetailItemActions.RESOLVE:
                                    if (widget.currentDiagnosisItems[index]
                                            .status ==
                                        "Deleted") {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyDeleted);
                                      return;
                                    }
                                    if (widget.currentDiagnosisItems[index]
                                            .resolved ==
                                        true) {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyResolved);
                                      return;
                                    }
                                    bool result = await model.resolveDiagnosis(
                                        widget.currentDiagnosisItems[index],
                                        widget.patientInfo);
                                    if (result) {
                                      model.getCurrentDiagnosisList(
                                          widget.patientInfo);
                                    }
                                    break;

                                  case SoapDetailItemActions.REMOVE:
                                    if (widget.currentDiagnosisItems[index]
                                            .status ==
                                        "Deleted") {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyDeleted);
                                      return;
                                    }
                                    if (widget.currentDiagnosisItems[index]
                                            .resolved ==
                                        true) {
                                      DrAppToastMsg.showErrorToast(
                                          TranslationBase.of(context)
                                              .diagnosisAlreadyResolved);
                                      return;
                                    }
                                    showConfirmationDialog(context,
                                        "${TranslationBase.of(context).delete} ${TranslationBase.of(context).diagnosis}",
                                        (remarks) {
                                      widget.model.removeDiagnosis(
                                          widget.patientInfo,
                                          widget.currentDiagnosisItems[index],
                                          remarks);
                                    });

                                  case SoapDetailItemActions.CHANGE_STATUS:
                                  // TODO: Handle this case.
                                  default:
                                }
                              },
                            );
                          },
                          separatorBuilder: (_, index) => Divider(),
                          itemCount: widget.currentDiagnosisItems.length))
                }
              ],
            ),
          );
        });
  }

  showConfirmationDialog(
      BuildContext context, String message, Function(String) okFunction) {
    return showDialog(
        context: context,
        barrierDismissible: true, // user must tap button!
        builder: (_) {
          return Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                AlertDialog(
                  title: null,
                  content: Container(
                    child: Column(
                      children: [
                        AppText(message),
                        SizedBox(
                          height: 8,
                        ),
                        AppText(
                          TranslationBase.of(context)
                              .areYouSureYouWantToDeleteDiagnosis,
                          textAlign: TextAlign.center,
                        ),
                        SizedBox(
                          height: 8,
                        ),
                        AppTextFieldCustom(
                          hintText: TranslationBase.of(context).remarks,
                          controller: deleteController,
                          maxLines: 25,
                          minLines: 3,
                          hasBorder: true,
                          onChanged: (value) {},
                          inputType: TextInputType.multiline,
                          onClick: () {},
                          onFieldSubmitted: () {},
                        ),
                      ],
                    ),
                  ),
                  actions: [
                    Row(
                      children: [
                        Expanded(
                          child: AppButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            title: TranslationBase.of(context).cancel,
                            fontColor: Colors.black,
                            color: Color(0xffEAEAEA),
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Expanded(
                          child: AppButton(
                            onPressed: () {
                              if (deleteController.text.isEmpty) {
                                DrAppToastMsg.showErrorToast(
                                    TranslationBase.of(context)
                                        .remarksCanNotBeEmpty);
                                return;
                                ;
                              }
                              okFunction(deleteController.text);
                              Navigator.of(context).pop();
                            },
                            title: TranslationBase.of(context).delete,
                            fontColor: Colors.white,
                            color: Colors.red[600],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          );
        }).then((value) {
      deleteController.clear();
    });
  }

  void showAuditBottomSheet(
    BuildContext context,
    List<AuditDiagnosis> diagnosis,
    void Function(bool status) toggleShowBottomSheetValue,
  ) {
    showModalBottomSheet(
      isDismissible: true,
      context: context,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20), topRight: Radius.circular(20))),
      builder: (_) {
        return AuditListBottomSheet(
          auditList: diagnosis,
        );
      },
    ).then((value) => toggleShowBottomSheetValue(false));
  }
}
