import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/enums.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/route_extensions.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/services/navigation_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';

class LoaderBottomSheet {
  static final NavigationService _navService = GetIt.I<NavigationService>();
  static bool _isVisible = false;

  static void showLoader({String? loadingText, bool showCloseButton = false, Function? onCloseTap}) {
    if (_isVisible) return;

    _isVisible = true;

    final context = _navService.navigatorKey.currentContext!;
    showModalBottomSheet(
      context: context,
      isDismissible: (ApiConsts.appEnvironmentType == AppEnvironmentTypeEnum.uat || kDebugMode) ? true : false,
      enableDrag: false,
      constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width),
      backgroundColor: Colors.transparent,
      builder: (_) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.3,
          decoration: BoxDecoration(
            color: AppColors.whiteColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: (showCloseButton) ? Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  "".toText20(),
                  if (showCloseButton)
                    IconButton(
                      icon: Icon(Icons.close, color: AppColors.textColor),
                      onPressed: () {
                        context.pop();
                        if(onCloseTap != null) {
                          onCloseTap();
                        }
                      },
                    )
                  else
                    SizedBox(width: 48), // Placeholder for alignment
                ],
              ),
              Center(
                child: Utils.getLoadingWidget(loadingText: loadingText),
              ).paddingSymmetrical(24.w, 0),
            ],
          ) : Center(
            child: Utils.getLoadingWidget(loadingText: loadingText),
          ).paddingSymmetrical(24.w, 0),
        );
      },
    ).whenComplete(() {
      // reset state if dismissed by system
      _isVisible = false;
    });
  }

  static void hideLoader() {
    if (_isVisible) {
      Navigator.of(_navService.navigatorKey.currentContext!).pop();
      _isVisible = false;
    }
  }
}
