import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/OrderDisplay.dart';
import 'package:hmg_patient_app_new/features/location/location_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/RRT/rrt_request_type_select.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/WayPickup.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/ambulance_option_selection_bottomsheet.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/call_ambulance/widgets/pickup_location.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/er_online_checkin/er_online_checkin_home.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/history/er_history_listing.dart';
import 'package:hmg_patient_app_new/presentation/home/service_info_page.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';

import '../../features/emergency_services/models/AmbulanceCallingPlace.dart' show AmbulanceCallingPlace;

class EmergencyServicesPage extends StatefulWidget {
  EmergencyServicesPage({super.key});

  @override
  State<EmergencyServicesPage> createState() => _EmergencyServicesPageState();
}

class _EmergencyServicesPageState extends State<EmergencyServicesPage> {
  late EmergencyServicesViewModel emergencyServicesViewModel;

  late AppState appState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (appState.isAuthenticated) {
        emergencyServicesViewModel.flushData();
        emergencyServicesViewModel.getTransportationOrders(
          showLoader: false,
        );
        emergencyServicesViewModel.getRRTOrders(
          showLoader: false,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    emergencyServicesViewModel = Provider.of<EmergencyServicesViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return CollapsingListView(
      title: LocaleKeys.emergencyServices.tr(),
      history: appState.isAuthenticated
          ? () {
              emergencyServicesViewModel.changeOrderDisplayItems(OrderDislpay.ALL);
              Navigator.of(context).push(CustomPageRoute(page: ErHistoryListing(), direction: AxisDirection.up));
            }
          : null,
      child: Padding(
        padding: EdgeInsets.all(24.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.all(16.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 20.h,
                hasShadow: false,
              ),
              child: Row(
                children: [
                  Utils.buildSvgWithAssets(icon: AppAssets.call_ambulance_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                  SizedBox(width: 12.h),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.callAmbulance.tr().toText16(isBold: true, color: AppColors.blackColor),
                          LocaleKeys.requestAmbulanceInEmergency.tr().toText12(color: AppColors.greyTextColor, isBold: true),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.h),
                  Transform.flip(
                    flipX: appState.isArabic(),
                    child: Utils.buildSvgWithAssets(icon: AppAssets.forward_chevron_icon, width: 13.h, height: 13.h),
                  ),
                ],
              ).onPress(() {
                if(appState.isAuthenticated) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.primaryRedColor,
                        borderRadius: 24.h,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(24.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                "".toText14(),
                                Utils.buildSvgWithAssets(
                                  icon: AppAssets.cancel_circle_icon,
                                  iconColor: Colors.white,
                                  width: 24.h,
                                  height: 24.h,
                                  fit: BoxFit.contain,
                                ).onPress(() {
                                  Navigator.of(context).pop();
                                }),
                              ],
                            ),
                            Lottie.asset(AppAnimations.ambulanceAlert, repeat: false, reverse: false, frameRate: FrameRate(60), width: 120.h, height: 120.h, fit: BoxFit.contain),
                            SizedBox(height: 8.h),
                            LocaleKeys.confirmation.tr().toText28(color: Colors.white, isBold: true),
                            SizedBox(height: 8.h),
                            LocaleKeys.areYouSureYouWantToCallAmbulance.tr().toText14(color: Colors.white, isBold: true),
                            SizedBox(height: 24.h),
                            CustomButton(
                              text: LocaleKeys.confirm.tr(context: context),
                              onPressed: () async {
                                Navigator.of(context).pop();
                                await emergencyServicesViewModel.getTransportationOption();
                                openTranportationSelectionBottomSheet(context);
                              },
                              backgroundColor: Colors.white,
                              borderColor: Colors.white,
                              textColor: AppColors.primaryRedColor,
                              icon: AppAssets.checkmark_icon,
                              iconColor: AppColors.primaryRedColor,
                            ),
                            SizedBox(height: 8.h),
                          ],
                        ),
                      ),
                    ),
                    isFullScreen: false,
                    isCloseButtonVisible: false,
                    hasBottomPadding: false,
                    backgroundColor: AppColors.primaryRedColor,
                    callBackFunc: () {},
                  );
                } else {
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: ServiceInfoPage(
                          serviceName: LocaleKeys.emergencyServices.tr(),
                          serviceHeader: LocaleKeys.callAmbulance.tr(),
                          serviceDescription: LocaleKeys.requestAmbulanceInEmergency.tr(),
                          serviceImage: AppAssets.ambulance_section),
                    ),
                  );
                }
              }),
            ),
            SizedBox(height: 16.h),
            Container(
              padding: EdgeInsets.all(16.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 20.h,
                hasShadow: false,
              ),
              child: Row(
                children: [
                  Utils.buildSvgWithAssets(icon: AppAssets.nearest_er_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                  SizedBox(width: 12.h),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.nearester.tr(context: context).toText16(isBold: true, color: AppColors.blackColor),
                        LocaleKeys.getDetailsOfNearestBranch.tr().toText12(color: AppColors.greyTextColor, isBold: true),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.h),
                  Transform.flip(
                    flipX: appState.isArabic(),
                    child: Utils.buildSvgWithAssets(icon: AppAssets.forward_chevron_icon, width: 13.h, height: 13.h),
                  ),
                ],
              ).onPress(() {
                context.read<EmergencyServicesViewModel>().navigateToNearestERPage();
              }),
            ),
            SizedBox(height: 16.h),
            Container(
              padding: EdgeInsets.all(16.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 20.h,
                hasShadow: false,
              ),
              child: Row(
                children: [
                  Utils.buildSvgWithAssets(icon: AppAssets.rrt_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                  SizedBox(width: 12.h),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.rapidResponseTeam.tr(context: context).toText16(isBold: true, color: AppColors.blackColor),
                        LocaleKeys.RRTDDetails.tr(context: context).toText12(color: AppColors.greyTextColor, isBold: true),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.h),
                  Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_chevron_icon, width: 13.h, height: 13.h)),
                ],
              ).onPress(() {
                if(appState.isAuthenticated) {
                  showCommonBottomSheetWithoutHeight(
                    context,
                    child: Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.primaryRedColor,
                        borderRadius: 24.h,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(24.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                "".toText14(),
                                Utils.buildSvgWithAssets(
                                  icon: AppAssets.cancel_circle_icon,
                                  iconColor: Colors.white,
                                  width: 24.h,
                                  height: 24.h,
                                  fit: BoxFit.contain,
                                ).onPress(() {
                                  Navigator.of(context).pop();
                                }),
                              ],
                            ),
                            Lottie.asset(AppAnimations.ambulanceAlert, repeat: false, reverse: false, frameRate: FrameRate(60), width: 120.h, height: 120.h, fit: BoxFit.contain),
                            SizedBox(height: 8.h),
                            LocaleKeys.confirm.tr().toText28(color: Colors.white, isBold: true),
                            SizedBox(height: 8.h),
                            LocaleKeys.areYouSureYouWantToCallRRT.tr().toText14(color: Colors.white, isBold: true),
                            SizedBox(height: 24.h),
                            CustomButton(
                              text: LocaleKeys.confirm.tr(context: context),
                              onPressed: () async {
                                Navigator.of(context).pop();
                                LoaderBottomSheet.showLoader();
                                emergencyServicesViewModel.clearRRTData();
                                await emergencyServicesViewModel.getRRTProcedures(onSuccess: (val) {
                                  LoaderBottomSheet.hideLoader();
                                  showCommonBottomSheetWithoutHeight(
                                    padding: EdgeInsets.only(top: 24.h),
                                    titleWidget: Transform.flip(
                                      flipX: emergencyServicesViewModel.isArabic,
                                      child: Utils.buildSvgWithAssets(
                                        icon: AppAssets.arrow_back,
                                        iconColor: Color(0xff2B353E),
                                        fit: BoxFit.contain,
                                      ),
                                    ).onPress(() {
                                      Navigator.pop(context);
                                    }),
                                    // title: "Rapid Response Team (RRT)".needTranslation,
                                    context,
                                    child: RrtRequestTypeSelect(),
                                    isFullScreen: false,
                                    isCloseButtonVisible: true,
                                    hasBottomPadding: false,
                                    backgroundColor: AppColors.bottomSheetBgColor,
                                    callBackFunc: () {},
                                  );
                                });
                              },
                              backgroundColor: Colors.white,
                              borderColor: Colors.white,
                              textColor: AppColors.primaryRedColor,
                              icon: AppAssets.checkmark_icon,
                              iconColor: AppColors.primaryRedColor,
                            ),
                            SizedBox(height: 8.h),
                          ],
                        ),
                      ),
                    ),
                    isFullScreen: false,
                    isCloseButtonVisible: false,
                    hasBottomPadding: false,
                    backgroundColor: AppColors.primaryRedColor,
                    callBackFunc: () {
                      context.read<EmergencyServicesViewModel>().setTermsAndConditions(false);
                    },
                  );
                } else {
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: ServiceInfoPage(
                          serviceName: LocaleKeys.emergencyServices.tr(),
                          serviceHeader: LocaleKeys.rapidResponseTeam.tr(),
                          serviceDescription: LocaleKeys.RRTDDetails.tr(),
                          serviceImage: AppAssets.rrt_section),
                    ),
                  );
                }
              }),
            ),
            SizedBox(height: 16.h),
            Container(
              padding: EdgeInsets.all(16.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 20.h,
                hasShadow: false,
              ),
              child: Row(
                children: [
                  Utils.buildSvgWithAssets(icon: AppAssets.rrt_icon, width: 40.h, height: 40.h, applyThemeColor: false),
                  SizedBox(width: 12.h),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        LocaleKeys.emergencyCheckIn.tr(context: context).toText16(isBold: true, color: AppColors.blackColor),
                        LocaleKeys.priorERCheckInToSkipLine.tr().toText12(color: AppColors.greyTextColor, isBold: true),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.h),
                  Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.forward_chevron_icon, width: 13.h, height: 13.h)),
                ],
              ).onPress(() {
                if(appState.isAuthenticated) {
                  if (emergencyServicesViewModel.patientHasAdvanceERBalance) {
                    Navigator.of(context).push(CustomPageRoute(page: ErOnlineCheckinHome()));
                  } else {
                    showCommonBottomSheetWithoutHeight(
                      context,
                      child: Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.primaryRedColor, borderRadius: 24.h),
                        child: Padding(
                          padding: EdgeInsets.all(24.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  "".toText14(),
                                  Utils.buildSvgWithAssets(
                                    icon: AppAssets.cancel_circle_icon,
                                    iconColor: AppColors.whiteColor,
                                    width: 24.h,
                                    height: 24.h,
                                    fit: BoxFit.contain,
                                  ).onPress(() {
                                    Navigator.of(context).pop();
                                  }),
                                ],
                              ),
                              Lottie.asset(AppAnimations.ambulanceAlert, repeat: false, reverse: false, frameRate: FrameRate(60), width: 120.h, height: 120.h, fit: BoxFit.contain),
                              SizedBox(height: 8.h),
                              LocaleKeys.confirm.tr().toText28(color: Colors.white, isBold: true),
                              SizedBox(height: 8.h),
                              LocaleKeys.areYouSureYouWantToMakeERCheckIn.tr().toText14(color: Colors.white, isBold: true),
                              SizedBox(height: 24.h),
                              CustomButton(
                                text: LocaleKeys.confirm.tr(context: context),
                                onPressed: () async {
                                  Navigator.of(context).pop();
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingYourERAppointmentStatus.tr());
                                  await context.read<EmergencyServicesViewModel>().checkPatientERAdvanceBalance(onSuccess: (dynamic response) {
                                    LoaderBottomSheet.hideLoader();
                                    context.read<EmergencyServicesViewModel>().navigateToEROnlineCheckIn();
                                  });
                                },
                                backgroundColor: Colors.white,
                                borderColor: Colors.white,
                                textColor: AppColors.primaryRedColor,
                                icon: AppAssets.checkmark_icon,
                                iconColor: AppColors.primaryRedColor,
                              ),
                              SizedBox(height: 8.h),
                            ],
                          ),
                        ),
                      ),
                      isFullScreen: false,
                      isCloseButtonVisible: false,
                      hasBottomPadding: false,
                      backgroundColor: AppColors.primaryRedColor,
                      callBackFunc: () {},
                    );
                  }
                } else {
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: ServiceInfoPage(
                          serviceName: LocaleKeys.emergencyServices.tr(),
                          serviceHeader: LocaleKeys.emergencyCheckIn.tr(),
                          serviceDescription: LocaleKeys.priorERCheckInToSkipLine.tr(),
                          serviceImage: AppAssets.er_checkin),
                    ),
                  );
                }
              }),
            ),
          ],
        ),
      ),
    );
  }

  openPickupDetailsBottomSheet(BuildContext context) {
    showCommonBottomSheetWithoutHeight(
      onCloseClicked: () {
        context.read<EmergencyServicesViewModel>().flushPickupInformation();
      },
      titleWidget: Transform.flip(
        flipX: emergencyServicesViewModel.isArabic,
        child: Utils.buildSvgWithAssets(
          icon: AppAssets.arrow_back,
          iconColor: Color(0xff2B353E),
          fit: BoxFit.contain,
        ),
      ).onPress(() {
        context.read<EmergencyServicesViewModel>().flushPickupInformation();
        Navigator.pop(context);
        openTranportationSelectionBottomSheet(context);
      }),
      context,
      child: PickupLocation(onTap: (fromLocation) {
        Navigator.of(context).pop();
        if(fromLocation == AmbulanceCallingPlace.TO_HOSPITAL){
          openNumberWayOfSelectionBottomSheet(context);
          return;
        }
        context.read<LocationViewModel>().flushSearchPredictions();
        context.read<EmergencyServicesViewModel>().navigateTOAmbulancePage();
      }),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {},
    );
  }

  openNumberWayOfSelectionBottomSheet(BuildContext context) {
    showCommonBottomSheetWithoutHeight(
      onCloseClicked: () {
        context.read<EmergencyServicesViewModel>().flushPickupInformation();
      },
      titleWidget: Transform.flip(
        flipX: emergencyServicesViewModel.isArabic,
        child: Utils.buildSvgWithAssets(
          icon: AppAssets.arrow_back,
          iconColor: Color(0xff2B353E),
          fit: BoxFit.contain,
        ),
      ).onPress(() {
        context.read<EmergencyServicesViewModel>().flushPickupInformation();
        Navigator.pop(context);
        openPickupDetailsBottomSheet(context);
      }),
      context,
      child: WayPickup(onTap: () {
        Navigator.of(context).pop();
        context.read<LocationViewModel>().flushSearchPredictions();
        context.read<EmergencyServicesViewModel>().navigateTOAmbulancePage();
      }),
      isFullScreen: false,
      isCloseButtonVisible: true,
      hasBottomPadding: false,
      backgroundColor: AppColors.bottomSheetBgColor,
      callBackFunc: () {},
    );
  }

  void openTranportationSelectionBottomSheet(BuildContext context) {
    if (emergencyServicesViewModel.transportationOptions.isNotEmpty) {
      showCommonBottomSheetWithoutHeight(
        title: LocaleKeys.transportOptions.tr(),
        context,
        child: SizedBox(
          height: 500.h,
          child: AmbulanceOptionSelectionBottomSheet(onTap: () {
            Navigator.of(context).pop();
            openPickupDetailsBottomSheet(context);
            // context
            //     .read<EmergencyServicesViewModel>()
            //     .navigateTOAmbulancePage();
          }),
        ),
        isFullScreen: false,
        isCloseButtonVisible: true,
        hasBottomPadding: false,
        backgroundColor: AppColors.bottomSheetBgColor,
        callBackFunc: () {},
      );
    }
  }
}
