import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_general_instructions_response_model.dart';
import 'package:hmg_patient_app/pages/InPatientServices/admission_notice.dart';
import 'package:hmg_patient_app/pages/InPatientServices/birth_notification.dart';
import 'package:hmg_patient_app/pages/InPatientServices/general_instructions.dart';
import 'package:hmg_patient_app/pages/InPatientServices/help_PRO.dart';
import 'package:hmg_patient_app/pages/InPatientServices/inpatient_advance_payment.dart';
import 'package:hmg_patient_app/pages/InPatientServices/inpatient_general_consent.dart';
import 'package:hmg_patient_app/pages/InPatientServices/meal_plan.dart';
import 'package:hmg_patient_app/pages/InPatientServices/medical_instructions.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.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/widgets/data_display/medical/medical_profile_item.dart';
import 'package:hmg_patient_app/widgets/dialogs/alert_dialog.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_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/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../models/InPatientServices/get_inpatient_advance_requests_response_model.dart';
import '../../models/InPatientServices/get_medical_instructions_response_model.dart';

class InPatientServicesHome extends StatefulWidget {
  @override
  State<InPatientServicesHome> createState() => _InPatientServicesHomeState();
}

class _InPatientServicesHomeState extends State<InPatientServicesHome> {
  late ProjectViewModel projectViewModel;
  InPatientAdvanceResponseModel inPatientAdvanceResponseModel = InPatientAdvanceResponseModel();
  bool isReceivePrescriptionEnabled = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      checkDischargeMedications(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    List<Widget> inPatientServiceList = getInPatientServicesList(context);
    return AppScaffold(
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      appBarTitle: TranslationBase.of(context).InPatientServicesHeader,
      body: Container(
        margin: EdgeInsets.all(20.0),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(left: 12, right: 12),
              child: GridView.builder(
                shrinkWrap: true,
                primary: false,
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 2 / 2, crossAxisSpacing: 12, mainAxisSpacing: 12),
                padding: EdgeInsets.zero,
                itemCount: inPatientServiceList.length,
                itemBuilder: (BuildContext context, int index) {
                  return inPatientServiceList[index];
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> getInPatientServicesList(BuildContext context) {
    List<Widget> serviceList = [];

    serviceList.add(
      InkWell(
        onTap: () {
          openPatientGeneralConsent();
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).generalConsentTitle,
          imagePath: 'general_instructions.svg',
          subTitle: TranslationBase.of(context).generalConsentSubTitle,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
          isEnable: true,
        ),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          if (projectViewModel.isPatientAdmitted ? true : checkAdmissionRequestDate()) openGeneralInstructions(context);
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).generalInstructionsTitle,
          imagePath: 'general_instructions.svg',
          subTitle: TranslationBase.of(context).generalInstructionsSubTitle,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
          isEnable: projectViewModel.isPatientAdmitted ? true : checkAdmissionRequestDate(),
        ),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          if (projectViewModel.isPatientAdmitted ? true : checkAdmissionRequestDate()) openMedicalInstructions(context);
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).medicalInstructionsTitle,
          imagePath: 'medical_instructions.svg',
          subTitle: TranslationBase.of(context).medicalInstructionsSubTitle,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
          isEnable: projectViewModel.isPatientAdmitted ? true : checkAdmissionRequestDate(),
        ),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          if (projectViewModel.isPatientAdmitted) {
            Navigator.push(context, FadePage(page: MealPlanPage()));
          } else {
            AppToast.showErrorToast(message: "This service is only available to admitted patients");
          }
        },
        child: MedicalProfileItem(
            title: TranslationBase.of(context).mealPlanTitle,
            imagePath: 'meal_plan.svg',
            subTitle: TranslationBase.of(context).mealPlanSubTitle,
            width: 50.0,
            height: 40.0,
            isInPatient: true,
            isEnable: projectViewModel.isPatientAdmitted),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          openBirthNotificationsPage(context);
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).birthNotificationTitle,
          imagePath: 'birth_notification.svg',
          subTitle: TranslationBase.of(context).birthNotificationSubTitle,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
        ),
      ),
    );

    // serviceList.add(
    //   InkWell(
    //     onTap: () {
    //       // Navigator.push(context, FadePage(page: AdvancePaymentPage()));
    //     },
    //     child: MedicalProfileItem(
    //       title: TranslationBase.of(context).admissionNoticeTitle,
    //       imagePath: 'admission_notice.svg',
    //       subTitle: TranslationBase.of(context).admissionNoticeSubTitle,
    //       width: 50.0,
    //       height: 40.0,
    //       isInPatient: true,
    //     ),
    //   ),
    // );

    serviceList.add(
      InkWell(
        onTap: () {
          getInPatientAdvancePaymentRequests(context);
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).advancePayment,
          imagePath: 'advance_payment.svg',
          subTitle: TranslationBase.of(context).payment,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
        ),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          Navigator.push(context, FadePage(page: AdmissionNotice()));
          // if (isReceivePrescriptionEnabled) receivePrescriptionAPI(context);
        },
        child: MedicalProfileItem(
            title: TranslationBase.of(context).admissionNoticeTitle,
            imagePath: 'admission_notice.svg',
            subTitle: TranslationBase.of(context).admissionNoticeSubTitle,
            width: 50.0,
            height: 40.0,
            isInPatient: true,
            isEnable: true),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          // Navigator.push(context, FadePage(page: AdvancePaymentPage()));
          if (isReceivePrescriptionEnabled) receivePrescriptionAPI(context);
        },
        child: MedicalProfileItem(
            title: TranslationBase.of(context).receive,
            imagePath: 'receive_prescription.svg',
            subTitle: TranslationBase.of(context).prescriptions,
            width: 50.0,
            height: 40.0,
            isInPatient: true,
            isEnable: isReceivePrescriptionEnabled),
      ),
    );

    serviceList.add(
      InkWell(
        onTap: () {
          checkCurrentTime(context);
        },
        child: MedicalProfileItem(
          title: TranslationBase.of(context).help,
          imagePath: 'help_pro.svg',
          subTitle: TranslationBase.of(context).PRO,
          width: 50.0,
          height: 40.0,
          isInPatient: true,
        ),
      ),
    );

    return serviceList;
  }

  void receivePrescriptionAPI(BuildContext context) {
    AlertDialogBox(
        context: context,
        confirmMessage: TranslationBase.of(context).successSendReport,
        okText: TranslationBase.of(context).ok,
        okFunction: () {
          AlertDialogBox.closeAlertDialog(context);
          callReceivePrescriptionAPI(context);
        }).showAlertDialog(context);

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

  void checkDischargeMedications(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getDischargeMedicationOrder(projectViewModel.getAdmissionInfoResponseModel).then((res) {
      setState(() {
        if (res["PatientHasDischargeMedicineList"].length != 0) {
          isReceivePrescriptionEnabled = true;
        }
      });
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  void callReceivePrescriptionAPI(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service
        .insertInPatientOrder(projectViewModel.getAdmissionInfoResponseModel, 2, (projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!),
            (projectViewModel.user.firstNameN! + " " + projectViewModel.user.lastNameN!), projectViewModel.user.mobileNumber!, "I need my medicines", context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  void openBirthNotificationsPage(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service
        .getBirthNotification(
            projectViewModel.user.patientID!,
            projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.projectID! : projectViewModel.getAdmissionRequestInfoResponseModel.projectId!,
            projectViewModel.isArabic ? 1 : 2,
            context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["MessageStatus"] == 1) {
        Navigator.push(context, FadePage(page: BirthNotification()));
      } else {
        AppToast.showErrorToast(message: res["endUserMessage"], localContext: context);
      }
    }).catchError((err) {
      print(err);
    });
  }

  void openPatientGeneralConsent() {
    Navigator.push(context, FadePage(page: InPatientGeneralConsent()));
  }

  void openGeneralInstructions(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getGeneralInstructions(projectViewModel.inPatientProjectID, projectViewModel.isArabic ? 1 : 2, context).then((res) {
      if (res['generalInstructions'].length != 0) {
        List<GetGeneralInstructions> getGeneralInstructionsList = [];
        res['generalInstructions'].forEach((v) {
          getGeneralInstructionsList.add(new GetGeneralInstructions.fromJson(v));
        });
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.push(context, FadePage(page: GeneralInstructions(getGeneralInstructionsList: getGeneralInstructionsList)));
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: TranslationBase.of(context).noGeneralInstructions);
      }
    }).catchError((err) {
      print(err);
    });
  }

  void openMedicalInstructions(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getMedicalInstructions(projectViewModel.inPatientProjectID, projectViewModel.isArabic ? 1 : 2, context).then((res) {
      if (res['MedicalInstruction'] != null && res['MedicalInstruction'].length != 0) {
        List<GetMedicalInstructions> getMedicalInstructionsList = [];
        res['MedicalInstruction'].forEach((v) {
          getMedicalInstructionsList.add(new GetMedicalInstructions.fromJson(v));
        });
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.push(context, FadePage(page: MedicalInstructionsPage(getMedicalInstructionsList: getMedicalInstructionsList)));
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: TranslationBase.of(context).noMedicalInstructions);
      }
    }).catchError((err) {
      print(err);
    });
  }

  void getInPatientAdvancePaymentRequests(BuildContext context) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service
        .getInPatientAdvancePaymentRequests(
            projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.projectID! : projectViewModel.getAdmissionRequestInfoResponseModel.projectId!,
            projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.admissionNo! : 0,
            projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.admissionRequestNo! : projectViewModel.getAdmissionRequestInfoResponseModel.admissionRequestNo!,
            projectViewModel.isArabic ? 1 : 2,
            context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["MessageStatus"] == 1) {
        if (res['responseInpatient'] != null && res['responseInpatient']['responseInpatientAdvanceInfo'] != null && res['responseInpatient']['responseInpatientAdvanceInfo'].length != 0) {
          inPatientAdvanceResponseModel = InPatientAdvanceResponseModel.fromJson(res["responseInpatient"]);
          Navigator.push(context,
              FadePage(page: InPatientAdvancePayment(isHasData: inPatientAdvanceResponseModel.responseInpatientAdvanceInfo != null, inPatientAdvanceResponseModel: inPatientAdvanceResponseModel)));
        } else {
          AppToast.showErrorToast(message: TranslationBase.of(context).noData);
        }
      } else {
        Navigator.push(context,
            FadePage(page: InPatientAdvancePayment(isHasData: inPatientAdvanceResponseModel.responseInpatientAdvanceInfo != null, inPatientAdvanceResponseModel: inPatientAdvanceResponseModel)));
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  void checkCurrentTime(BuildContext context) {
    if (DateTime.now().hour >= 7 && DateTime.now().hour <= 22) {
      Navigator.push(context, FadePage(page: HelpPRO()));
    } else {
      ConfirmDialog dialog = new ConfirmDialog(
          context: context,
          confirmMessage: TranslationBase.of(context).proErrorMessage,
          okText: TranslationBase.of(context).callNow,
          cancelText: TranslationBase.of(context).cancel_nocaps,
          okFunction: () => {ConfirmDialog.closeAlertDialog(context), launchUrl(Uri.parse("tel://" + "011 525 9553"))},
          cancelFunction: () => {});
      dialog.showAlertDialog(context);
    }
  }

  bool checkAdmissionRequestDate() {
    if (DateUtil.convertStringToDate(projectViewModel.getAdmissionRequestInfoResponseModel.expectedAdmissionDate).difference(DateTime.now()).inHours > 24) {
      return false;
    }
    return true;
  }
}
