import 'dart:convert';
import 'dart:developer';
import 'package:frontend_eccp_mobile/app/core/constants/globalkey.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_routes.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/data/model/user_session.dart';

class NotificationRouter {
  NotificationRouter._();
  static Future<void> handle(Map<String, dynamic> data) async {
    log('NotificationRouter.handle: $data', name: 'FCM');

    final page = data['page']?.toString();
    if (page == null || page.isEmpty) {
      log('Missing page in notification payload', name: 'FCM');
      return;
    }

    Map<String, dynamic>? params;

    final paramsRaw = data['params'];
    if (paramsRaw is String && paramsRaw.isNotEmpty) {
      try {
        params = jsonDecode(paramsRaw) as Map<String, dynamic>;
      } catch (_) {
        log('Failed to decode params string', name: 'FCM');
      }
    } else if (paramsRaw is Map<String, dynamic>) {
      params = paramsRaw;
    }

    params ??= Map<String, dynamic>.from(data)
      ..remove('page')
      ..remove('notification');

    if (params.isEmpty) params = null;

    await _navigate(page: page, params: params);
  }

  static Future<void> handleRaw(String raw) async {
    log('NotificationRouter.handleRaw: $raw', name: 'FCM');

    if (raw.trim().isEmpty) return;

    try {
      final decoded = jsonDecode(raw);
      if (decoded is Map<String, dynamic>) {
        await handle(decoded);
        return;
      }
    } catch (_) {}

    if (raw.contains('=') && raw.contains('&')) {
      try {
        final uri = Uri(query: raw);
        await handle(Map<String, dynamic>.from(uri.queryParameters));
        return;
      } catch (_) {}
    }

    try {
      final normalized = raw
          .replaceAll('{', '')
          .replaceAll('}', '')
          .split(',')
          .map((e) => e.split(':'))
          .where((e) => e.length == 2)
          .fold<Map<String, dynamic>>({}, (map, pair) {
            final key = pair[0].trim();
            final value = pair[1].trim();

            map[key] = int.tryParse(value) ?? value;
            return map;
          });

      if (normalized.isNotEmpty) {
        await handle(normalized);
        return;
      }
    } catch (_) {}

    log('handleRaw failed to parse payload', name: 'FCM');
  }

  static Future<void> _navigate({
    required String? page,
    Map<String, dynamic>? params,
  }) async {
    final navContext = navigatorKey.currentContext;
    if (navContext == null) return;

    if (!navContext.mounted) return;

    if (!getIt<UserSession>().isLoggedIn) {
      await AppNavigator.clearAndPush(
        navContext,
        AppRoutes.login,
      );
      return;
    }

    if (page != null) {
      if (!navContext.mounted) return;
      await NotificationRoutes.routeToPage(navContext, page, params);
    }
  }
}
