import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:frontend_eccp_mobile/app/core/di/injection.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_navigator.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_routes.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_route/notification_router.dart';
import 'package:frontend_eccp_mobile/app/core/notification/notification_intent_store.dart';
import 'package:frontend_eccp_mobile/app/core/services/crashlytics_service.dart';
import 'package:frontend_eccp_mobile/app/core/widgets/bottomsheet/app_bottom_sheet.dart';
import 'package:frontend_eccp_mobile/app/core/widgets/bottomsheet/appbottomsheet_controller.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/data/model/user_session.dart';
import 'package:frontend_eccp_mobile/modules/profile/bloc/logout/logout_cubit.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

class AuthHandler {
  AuthHandler._();

  static Future<void> handleAuth(BuildContext context) async {
    if (!context.mounted) return;

    if (getIt<UserSession>().isLoggedIn) {
      await AppNavigator.clearAndPush(
        context,
        AppRoutes.home,
        onOpened: () async {
          final data = NotificationIntentStore.consume();

          if (data != null) {
            await NotificationRouter.handle(data);
          }
        },
      );
    } else {
      await AppNavigator.clearAndPush(
        context,
        AppRoutes.login,
      );
    }
  }

  static Future<void> logout(BuildContext context) async {
    await showMaterialModalBottomSheet<dynamic>(
      context: context,
      backgroundColor: const Color.fromARGB(0, 213, 135, 135),
      builder: (_) {
        return AppBottomSheet(
          controller: AppBottomSheetController(),
          useSecondaryButton: true,
          title: 'Apakah anda yakin ingin keluar?',
          subTitle:
              'Jika ya, anda akan keluar dari aplikasi dan perlu login kembali.',
          primaryText: 'Keluar',
          secondaryText: 'Batal',
          onPrimaryPressed: () async {
            Navigator.pop(context);
            await CrashlyticsService.clearUser();
            getIt<UserSession>().clear();
            if (!context.mounted) return;
            await context.read<LogoutCubit>().logout();
          },
        );
      },
    );
  }
}
