import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/enums/demo_request_step.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/enums/work_order_next_step.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/modules/cm_module/cm_detail_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/activities_list_view.dart';
import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart';
import 'package:test_sa/modules/cm_module/views/components/verify_arrival_view.dart';
import 'package:test_sa/modules/cm_module/views/forms/asset_retired/verify_asset_detail.dart';
import 'package:test_sa/modules/demo_module/demo_extension_bottom_sheet.dart';
import 'package:test_sa/modules/demo_module/evaluation_form_page.dart';
import 'package:test_sa/modules/demo_module/models/demo_request_model.dart';
import 'package:test_sa/modules/demo_module/provider/demo_provider.dart';
import 'package:test_sa/modules/demo_module/update_demo-request_view.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/swipe_module/dialoge/acknowledge_work_dialog.dart';
import 'package:test_sa/providers/service_request_providers/reject_reason_provider.dart';

class FooterActionButton {
  static Widget footerContainer({required Widget child, required BuildContext context, bool safeAreaTop = true}) {
    return Container(
      alignment: Alignment.bottomCenter,
      padding: const EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 12),
      color: AppColor.background(context),
      child: SafeArea(top: safeAreaTop, child: child),
    );
  }

  static Widget requestDetailsFooterWidget(
      {required WorkOrderNextStepEnum workOrderNextStepStatus,
      List<Activities> activities = const [],
      required BuildContext context,
      Lookup? status,
      required UserProvider userProvider,
      bool isEmpIsAssigned = false}) {
    CMDetailProvider requestDetailProvider = Provider.of<CMDetailProvider>(context, listen: false);
    bool showMarkAsFixedButton = activities.isEmpty
        ? false
        : activities.any((object) =>
            object.activityStatus!.value == 14 || object.activityStatus!.value == 19 || object.activityStatus!.value == 11); // value 14,19,20 for fixed,out of scope and duplicate activity status
    if (userProvider.user?.type == UsersTypes.engineer) {
      if (workOrderNextStepStatus == WorkOrderNextStepEnum.assignToMe && isEmpIsAssigned) return const SizedBox();
      switch (workOrderNextStepStatus) {
        case WorkOrderNextStepEnum.assignToMe:
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: 'Assign To Me',
                // maxWidth: true,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  requestDetailProvider.engineerAssignWorkOrderToHimself(id: requestDetailProvider.currentWorkOrder!.data!.requestId.toString());
                },
                fontSize: 12.toScreenWidth,
              ));
        case WorkOrderNextStepEnum.markedAsFixed:
          break;
        // TODO: Handle this case.
        case WorkOrderNextStepEnum.endWorkFlow:
          if (requestDetailProvider.isReadOnlyRequest) {
            return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.activities,
                buttonColor: AppColor.neutral50,
                textColor: context.isDark ? AppColor.neutral30 : Colors.white,
                onPressed: () async {
                  Navigator.push(context, MaterialPageRoute(builder: (context) => const ActivitiesListView()));
                },
              ),
            );
          }
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.close,
                // maxWidth: true,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  Navigator.pop(context);
                },
              ));
        case WorkOrderNextStepEnum.nTakeAction:
          if (requestDetailProvider.isReadOnlyRequest) {
            return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.activities,
                buttonColor: context.isDark ? AppColor.primary10 : AppColor.neutral50,
                textColor: context.isDark ? AppColor.black10 : Colors.white,
                onPressed: () async {
                  Navigator.push(context, MaterialPageRoute(builder: (context) => const ActivitiesListView()));
                },
              ),
            );
          }
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.close,
                // maxWidth: true,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  Navigator.pop(context);
                },
              ));
        case WorkOrderNextStepEnum.eRejectAccept:
          return footerContainer(
              context: context,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  AppFilledButton(
                    label: context.translation.reject,
                    maxWidth: true,
                    buttonColor: AppColor.background(context),
                    // textColor: context.isDark ? AppColor.neutral30 : Colors.white,
                    textColor: AppColor.red30,
                    showBorder: true,
                    onPressed: () async {
                      //TODO need to discuss getData is not called by default...
                      if (context.mounted) {
                        RejectReasonProvider rejectionReasonProvider = Provider.of<RejectReasonProvider>(context, listen: false);
                        rejectionReasonProvider.reset();
                        //rejectionReasonProvider.getDate();
                      }
                      ServiceRequestBottomSheet.rejectRequestBottomSheet(context: context);
                    },
                  ).expanded,
                  const SizedBox(
                    width: 20,
                  ),
                  AppFilledButton(
                    label: context.translation.accept,
                    maxWidth: true,
                    buttonColor: AppColor.green70,
                    onPressed: () async {
                      requestDetailProvider.engineerAcceptWorkOrder(id: requestDetailProvider.currentWorkOrder!.data!.requestId.toString());
                    },
                  ).expanded,
                ],
              ));
        case WorkOrderNextStepEnum.eFixRemotelyNeedVisit:
          return footerContainer(
              context: context,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  AppFilledButton(
                    label: context.translation.needAVisit,
                    maxWidth: true,
                    buttonColor: AppColor.neutral50,
                    onPressed: () async {
                      requestDetailProvider.needVisitHelperModel = NeedVisitHelperModel();
                      ServiceRequestBottomSheet.initialVisitBottomSheet(context: context);
                    },
                  ).expanded,
                  const SizedBox(
                    width: 20,
                  ),
                  AppFilledButton(
                    label: context.translation.fixedRemotely,
                    maxWidth: true,
                    buttonColor: AppColor.green70,
                    onPressed: () async {
                      requestDetailProvider.fixRemotelyHelperModel = FixRemotelyHelperModel();
                      ServiceRequestBottomSheet.fixRemotelyBottomSheet(context: context);
                    },
                  ).expanded,
                ],
              ));
        case WorkOrderNextStepEnum.eArrived:
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.iHaveArrived,
                showIcon: true,
                icon: 'arrived_icon'.toSvgAsset(color: AppColor.background(context)),
                buttonColor: AppColor.green70,
                onPressed: () async {
                  Navigator.push(context, MaterialPageRoute(builder: (context) => const VerifyArrivalView()));
                },
              ));
        case WorkOrderNextStepEnum.verifyAssetDetail:
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.updateAssetDetails,
                // maxWidth: true,
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  Navigator.push(context, MaterialPageRoute(builder: (context) => VerifyAssetDetails(isEdit: false)));
                },
              ));
        case WorkOrderNextStepEnum.activity:
          return footerContainer(
              context: context,
              child: Column(
                children: [
                  AppFilledButton(
                    label: context.translation.activities,
                    buttonColor: AppColor.primary10,
                    onPressed: () async {
                      // ServiceRequestBottomSheet.activityTypeBottomSheet(context: context);
                      Navigator.push(context, MaterialPageRoute(builder: (context) => const ActivitiesListView()));
                    },
                  ),
                  if (showMarkAsFixedButton) ...[
                    8.height,
                    AppFilledButton(
                      label: context.translation.markAsCompleted,
                      // maxWidth: true,
                      buttonColor: AppColor.green70,
                      onPressed: () {
                        bool isValid = ServiceRequestBottomSheet.validateAssetSituation(Provider.of<CMDetailProvider>(context, listen: false));
                        if (isValid) {
                          showDialog(
                            context: context,
                            builder: (BuildContext cxt) => AcknowledgeWorkDialog(
                              message: "Are you sure you want to mark this Work Order as complete ",
                              confirmButtonText: 'Complete',
                              cancelButtonText: 'Cancel',
                              onSave: () async {
                                int status = await requestDetailProvider.engineerMarkAsFixed(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, feedback: '');
                                if (status != -1) {
                                  Navigator.of(cxt).pop();
                                }
                              },
                              onDiscard: () {},
                            ),
                          );
                        }
                        // ServiceRequestBottomSheet.feedBackBottomSheet(context: context);
                      },
                    ),
                  ]
                ],
              ));
        case WorkOrderNextStepEnum.endWorkFlow:
          return const SizedBox();

        case WorkOrderNextStepEnum.assetRetirementManagementApproval:
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.assetRetiredPendingOpManagementApproval,
                buttonColor: AppColor.background(context),
                textColor: context.isDark ? Colors.white : AppColor.neutral50,
                fontSize: 12.toScreenWidth,
              ));
        case WorkOrderNextStepEnum.waitingForRequesterToConfirm:
          return footerContainer(
              context: context,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AppFilledButton(
                    label: 'Waiting for requester to verify',
                    buttonColor: AppColor.background(context),
                    textColor: context.isDark ? Colors.white : AppColor.neutral50,
                    // buttonColor: AppColor.neutral140,
                    // textColor: AppColor.neutral150,
                    fontSize: 12.toScreenWidth,
                  ),
                  12.height,
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(Icons.info_outline_rounded, size: 16, color: context.isDark ? AppColor.neutral10 : AppColor.neutral120),
                      6.width,
                      Text(
                        "If you're experiencing issues with verification, please select another method to continue",
                        style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral120),
                      ).expanded,
                    ],
                  ),
                  12.height,
                  AppFilledButton(
                    label: "Switch Arrival Method",
                    showIcon: true,
                    buttonColor: AppColor.green70,
                    onPressed: () {
                      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                      Provider.of<CMDetailProvider>(context, listen: false).switchToIHaveArrived().then((value) {
                        Navigator.pop(context);
                        if (value) {
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const VerifyArrivalView()));
                        } else {
                          "Failed to switch, please try again".showToast;
                        }
                      });
                    },
                  )
                ],
              ));
        case WorkOrderNextStepEnum.eFixRemotely:
          return footerContainer(
            context: context,
            child: AppFilledButton(
              label: context.translation.fixedRemotely,
              maxWidth: true,
              buttonColor: AppColor.green70,
              onPressed: () async {
                requestDetailProvider.fixRemotelyHelperModel = FixRemotelyHelperModel();
                ServiceRequestBottomSheet.fixRemotelyBottomSheet(context: context);
              },
            ),
          );
        case WorkOrderNextStepEnum.eNeedVisit:
          return footerContainer(
              context: context,
              child: AppFilledButton(
                label: context.translation.needAVisit,
                maxWidth: true,
                textColor: context.isDark ? AppColor.neutral30 : Colors.white,
                buttonColor: AppColor.neutral50,
                onPressed: () async {
                  requestDetailProvider.needVisitHelperModel = NeedVisitHelperModel();
                  ServiceRequestBottomSheet.initialVisitBottomSheet(context: context);
                },
              ));
      }
    } else {
      if (workOrderNextStepStatus == WorkOrderNextStepEnum.nTakeAction) {
        return footerContainer(
            context: context,
            child: AppFilledButton(
              label: context.translation.takeAction,
              // maxWidth: true,
              buttonColor: AppColor.primary10,
              onPressed: () async {
                ServiceRequestBottomSheet.nurseTakeActionBottomSheet(context: context);
              },
            ));
      }
      if (workOrderNextStepStatus == WorkOrderNextStepEnum.waitingForRequesterToConfirm) {
        return footerContainer(
            context: context,
            child: AppFilledButton(
              label: context.translation.takeAction,
              // maxWidth: true,
              buttonColor: AppColor.primary10,
              onPressed: () async {
                ServiceRequestBottomSheet.nurseVerifyArrivalBottomSheet(context: context);
              },
            ));
      }
    }
    return const SizedBox();
  }

  static Widget demoRequestDetailsFooterWidget({
    required BuildContext context,
    Lookup? status,
    required DemoRequestModel dataModel,
    required DemoRequestStepEnum demoRequestStage,
    required VoidCallback refreshData,
  }) {
    DemoProvider demoProvider = Provider.of<DemoProvider>(context, listen: false);
    UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);

    if (userProvider.user?.type == UsersTypes.assessor) {
      switch (demoRequestStage) {
        case DemoRequestStepEnum.qAuditorRejectAccept:
          return footerContainer(
              context: context,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  AppFilledButton(
                    label: context.translation.reject,
                    maxWidth: true,
                    buttonColor: AppColor.background(context),
                    textColor: AppColor.red30,
                    showBorder: true,
                    onPressed: () async {
                      Utils.showLoading(context);
                      bool responseStatus = await demoProvider.acceptRejectRequest(requestId: dataModel.id!, status: false);
                      Utils.hideLoading(context);
                      if (responseStatus) {
                        Navigator.pop(context);
                      }
                    },
                  ).expanded,
                  const SizedBox(width: 16),
                  AppFilledButton(
                    label: context.translation.accept,
                    maxWidth: true,
                    buttonColor: AppColor.green70,
                    onPressed: () async {
                      Utils.showLoading(context);
                      bool responseStatus = await demoProvider.acceptRejectRequest(requestId: dataModel.id!, status: true);
                      Utils.hideLoading(context);
                      if (responseStatus) {
                        refreshData();
                      }
                    },
                  ).expanded,
                ],
              ));
        case DemoRequestStepEnum.updateRequest:
          return footerContainer(
            context: context,
            child: AppFilledButton(
              label: context.translation.updateRequest,
              // maxWidth: true,
              buttonColor: AppColor.primary10,
              onPressed: () async {
                bool? isRefresh = await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => UpdateDemoRequestView(
                              dataModel: dataModel,
                            )));
                if (isRefresh == true) {
                  refreshData();
                }
              },
            ),
          );
        case DemoRequestStepEnum.submitEvaluation:
          // return const SizedBox();
          // return footerContainer(
          //   context: context,
          //   child: AppFilledButton(
          //     label: 'Submit Evaluation'.addTranslation,
          //     // maxWidth: true,
          //     buttonColor: AppColor.primary10,
          //     onPressed: () async {
          //       bool? isRefresh = await Navigator.push(context, MaterialPageRoute(builder: (context) => EvaluationFormPage()));
          //       if (isRefresh == true) {
          //         refreshData();
          //       }
          //     },
          //   ),
          // );
          return const SizedBox();
        case DemoRequestStepEnum.viewOnly:
          return const SizedBox();
        case DemoRequestStepEnum.extendDemoPeriod:
          return footerContainer(
            context: context,
            child: AppFilledButton(
              buttonColor: AppColor.primary10,
              label: "Extension Request",
              onPressed: () async {
                final bool? isRefresh = await showModalBottomSheet<bool>(
                  context: context,
                  useSafeArea: true,
                  backgroundColor: Colors.transparent,
                  isScrollControlled: true,
                  builder: (_) => DemoExtensionBottomSheet(
                    requestId: dataModel.id!,
                  ),
                );
                if (isRefresh == true) {
                  refreshData();
                }
              },
            ),
          );
      }
    } else if (userProvider.user?.type == UsersTypes.normal_user) {
      switch (demoRequestStage) {
        case DemoRequestStepEnum.submitEvaluation:
          return footerContainer(
            context: context,
            child: AppFilledButton(
              label: 'Submit Evaluation'.addTranslation,
              // maxWidth: true,
              buttonColor: AppColor.primary10,
              onPressed: () async {
                bool? isRefresh = await Navigator.push(context, MaterialPageRoute(builder: (context) => EvaluationFormPage(id: dataModel.id!)));
                if (isRefresh == true) {
                  refreshData();
                }
              },
            ),
          );
        case DemoRequestStepEnum.viewOnly:
          return const SizedBox();
        case DemoRequestStepEnum.qAuditorRejectAccept:
          return const SizedBox();
        case DemoRequestStepEnum.updateRequest:
          return const SizedBox();
        case DemoRequestStepEnum.extendDemoPeriod:
          return footerContainer(
            context: context,
            child: AppFilledButton(
              buttonColor: AppColor.primary10,
              label: "Extension Request",
              onPressed: () async {
                final bool? isRefresh = await showModalBottomSheet<bool>(
                  context: context,
                  useSafeArea: true,
                  backgroundColor: Colors.transparent,
                  isScrollControlled: true,
                  builder: (_) => DemoExtensionBottomSheet(
                    requestId: dataModel.id!,
                  ),
                );
                if (isRefresh == true) {
                  refreshData();
                }
              },
            ),
          );
      }
    } else {
      if (demoRequestStage == DemoRequestStepEnum.viewOnly) {
        return const SizedBox();
      }
    }
    return const SizedBox();
  }
}
