import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/model/sick_leave/admission_status_for_sick_leave.dart';
import 'package:hmg_patient_app/core/model/sick_leave/sick_leave.dart';
import 'package:hmg_patient_app/core/service/medical/labs_service.dart';
import 'package:hmg_patient_app/core/viewModels/medical/patient_sick_leave_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/pages/medical/sickleave_workplace_update_page.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/data_display/medical/doctor_card.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_send_email_dialog.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class PatientSickLeavePage extends StatefulWidget {
  @override
  _PatientSickLeavePageState createState() => _PatientSickLeavePageState();
}

class _PatientSickLeavePageState extends State<PatientSickLeavePage> {
  List<ImagesInfo> imagesInfo = [];

  @override
  void initState() {
    imagesInfo.add(
        ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/imges-info/sick-leaves/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/imges-info/sick-leaves/ar/0.png'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<PatientSickLeaveViewMode>(
      onModelReady: (model) => model.getSickLeave(),
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).sickLeaves,
        description: TranslationBase.of(context).infoSickLeaves,
        infoList: TranslationBase.of(context).infoSickLeavePoints,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        backgroundColor: Color(0xffF7F7F7),
        imagesInfo: imagesInfo,
        baseViewModel: model,
        body: model.sickLeaveList.isNotEmpty
            ? ListView.separated(
                physics: BouncingScrollPhysics(),
                itemCount: model.sickLeaveList.length,
                padding: EdgeInsets.all(21),
                separatorBuilder: (context, index) => SizedBox(height: 14),
                itemBuilder: (context, index) => DoctorCard(
                  isLiveCareAppointment: model.sickLeaveList[index].isLiveCareAppointment,
                  name: model.sickLeaveList[index].doctorName,
                  date: model.sickLeaveList[index].appointmentDate,
                  profileUrl: model.sickLeaveList[index].doctorImageURL,
                  rating: model.sickLeaveList[index].actualDoctorRate!.toDouble(),
                  subName: model.sickLeaveList[index].clinicName,
                  isSortByClinic: false,
                  isInOutPatient: model.sickLeaveList[index].isInOutPatient,
                  isSickLeave: true,
                  sickLeaveStatus: model.sickLeaveList[index].status ?? 0,
                  onEmailTap: () {
                    showConfirmMessage(model, index);
                  },
                ),
              )
            : getNoDataWidget(context),
      ),
    );
  }

  void showConfirmMessage(PatientSickLeaveViewMode model, int index) {
    if (model.sickLeaveList[index].status == 1) {
      openWorkPlaceUpdatePage(model.sickLeaveList[index].requestNo!, model.sickLeaveList[index]!.setupID!, model, index, model.sickLeaveList[index]!.projectID!);
    } else if (model.sickLeaveList[index].status == 2) {
      // showEmailDialog(model, index);
      model.sendSickLeaveEmail(
          message: TranslationBase.of(context).emailSentSuccessfully,
          requestNo: model.sickLeaveList[index].requestNo!,
          doctorName: model.sickLeaveList[index].doctorName!,
          projectName: model.sickLeaveList[index].projectName!,
          setupID: model.sickLeaveList[index].setupID!,
          projectID: model.sickLeaveList[index].projectID!,
          isDownload: true);
    } else {
      showApprovalDialog();
    }
  }

  void showApprovalDialog() {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).needApproval,
        okText: TranslationBase.of(context).ok,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () {
          Navigator.of(context).pop();
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  void showEmailDialog(PatientSickLeaveViewMode model, int index) {
    showDialog(
      context: context,
      builder: (cxt) => ConfirmSendEmailDialog(
        email: model.user!.emailAddress!,
        onTapSendEmail: () {
          model.sendSickLeaveEmail(
              message: TranslationBase.of(context).emailSentSuccessfully,
              requestNo: model.sickLeaveList[index].requestNo!,
              doctorName: model.sickLeaveList[index].doctorName!,
              projectName: model.sickLeaveList[index].projectName!,
              setupID: model.sickLeaveList[index].setupID!,
              projectID: model.sickLeaveList[index].projectID!,
              isDownload: true);
          model.getSickLeave();
        },
      ),
    );
  }

  Future<void> openWorkPlaceUpdatePage(int requestNumber, String setupID, PatientSickLeaveViewMode model, int index, int projectID) async {
    if (model.sickLeaveList[index].admissionNo != 0 && model.sickLeaveList[index].admissionNo != null) {
      getSickLeaveStatusByAdmissionNo(requestNumber, setupID, model, index, projectID);
    } else {
      openWorkPlaceUpdatePageFunc(requestNumber, setupID, model, index, projectID);
    }
  }

  void getSickLeaveStatusByAdmissionNo(int requestNumber, String setupID, PatientSickLeaveViewMode model, int index, int projectID) {
    AdmissionStatusForSickLeave admissionStatusForSickLeave;

    LabsService service = new LabsService();
    GifLoaderDialogUtils.showMyDialog(context);

    service.getSickLeaveStatusByAdmissionNo(model.sickLeaveList[index]!.projectID!, model.sickLeaveList[index].admissionNo!).then((res) {
      print(res);
      GifLoaderDialogUtils.hideDialog(context);
      if (res != null && res["List_GetSickLeaveStatusByAdmissionNo"] != null) {
        if (res["List_GetSickLeaveStatusByAdmissionNo"].length != 0) {
          admissionStatusForSickLeave = AdmissionStatusForSickLeave.fromJson(res["List_GetSickLeaveStatusByAdmissionNo"][0]);
          if (admissionStatusForSickLeave.status != 6) {
            AppToast.showErrorToast(message: TranslationBase.of(context).sickLeaveAdmittedPatient);
          } else {
            openWorkPlaceUpdatePageFunc(requestNumber, setupID, model, index, projectID);
          }
        } else {
          openWorkPlaceUpdatePageFunc(requestNumber, setupID, model, index, projectID);
        }
      } else {
        openWorkPlaceUpdatePageFunc(requestNumber, setupID, model, index, projectID);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  void openWorkPlaceUpdatePageFunc(int requestNumber, String setupID, PatientSickLeaveViewMode model, int index, int projectID) {
    Navigator.push(
      context,
      FadePage(
        page: WorkplaceUpdatePage(
          requestNumber: requestNumber,
          setupID: setupID,
          projectID: projectID,
        ),
      ),
    ).then(
      (value) {
        print(value);
        if (value != null && value == true) {
          model.getSickLeave();
          // showEmailDialog(model, index);
          model.sendSickLeaveEmail(
              message: TranslationBase.of(context).emailSentSuccessfully,
              requestNo: model.sickLeaveList[index].requestNo!,
              doctorName: model.sickLeaveList[index].doctorName!,
              projectName: model.sickLeaveList[index].projectName!,
              setupID: model.sickLeaveList[index].setupID!,
              projectID: model.sickLeaveList[index].projectID!,
              isDownload: true);
        }
      },
    );
  }
}
