import 'package:flutter/material.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/features/authentication/widgets/otp_verification_screen.dart';
import 'package:hmg_patient_app_new/routes/app_routes.dart';

class NavigationService {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  final RouteObserver<PageRoute<dynamic>> routeObserver = RouteObserver<PageRoute<dynamic>>();

  BuildContext? get context => navigatorKey.currentContext;

  Future<T?> push<T>(Route<T> route) {
    return navigatorKey.currentState!.push(route);
  }

  Future<T?> pushAndRemoveUntil<T>(Route<T> route, RoutePredicate predicate) {
    return navigatorKey.currentState!.pushAndRemoveUntil(route, predicate);
  }

  void pop<T extends Object?>([T? result]) {
    navigatorKey.currentState!.pop(result);
  }

  void popUntilNamed(String routeName) {
    navigatorKey.currentState?.popUntil(ModalRoute.withName(routeName));
  }


  void replaceAllRoutesAndNavigateToLanding() {
    AppState appState = getIt.get<AppState>();
    appState.isAuthenticated = false;
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      AppRoutes.landingScreen,
      (Route<dynamic> route) => false,
    );
  }

  Future replaceAllRoutesAndNavigateToLandingWithMedicalAuth() async {
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      AppRoutes.landingScreen,
          (Route<dynamic> route) => false,
    );
  }

  void replaceAllRoutesAndNavigateToLandingAuth() {
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      AppRoutes.landingScreen,
          (Route<dynamic> route) => false,
    );
  }

  void pushAndReplace(String routeName) {
    navigatorKey.currentState?.pushReplacementNamed(routeName);
  }

  void pushPageRoute(String routeName) {
    navigatorKey.currentState?.pushNamed(routeName);
  }

  Future<T?> pushToOtpScreen<T>(
      {required String phoneNumber, required String zipCode, required Function(int code) checkActivationCode, required Function(String phoneNumber, String zipCode) onResendOTPPressed, bool isFormFamilyFile = false}) {
    return navigatorKey.currentState!.push(
      MaterialPageRoute(
          builder: (_) => OTPVerificationScreen(phoneNumber: phoneNumber, zipCode: zipCode, checkActivationCode: checkActivationCode, onResendOTPPressed: onResendOTPPressed, isFormFamilyFile: isFormFamilyFile)),
    );
  }

  Future<T?> pushPage<T>({
    required Widget page,
    bool fullscreenDialog = false,
    bool maintainState = true,
  }) {
    return navigatorKey.currentState!.push<T>(
      MaterialPageRoute(
        builder: (_) => page,
        fullscreenDialog: fullscreenDialog,
        maintainState: maintainState,
      ),
    );
  }
}
