import 'package:flutter/foundation.dart';
import 'package:adjust_sdk/adjust.dart';
import 'package:adjust_sdk/adjust_config.dart';
import 'package:adjust_sdk/adjust_event.dart';
import 'package:adjust_sdk/adjust_attribution.dart';
import 'package:adjust_sdk/adjust_event_success.dart';
import 'package:adjust_sdk/adjust_event_failure.dart';
import 'package:adjust_sdk/adjust_session_success.dart';
import 'package:adjust_sdk/adjust_session_failure.dart';
import 'package:shared_preferences/shared_preferences.dart';

typedef AdjustAttributionHandler = void Function(AdjustAttribution a);
typedef AdjustEventSuccessHandler = void Function(AdjustEventSuccess s);
typedef AdjustEventFailureHandler = void Function(AdjustEventFailure f);
typedef AdjustSessionSuccessHandler = void Function(AdjustSessionSuccess s);
typedef AdjustSessionFailureHandler = void Function(AdjustSessionFailure f);

class AdjustBridge {
  AdjustBridge._();
  static final AdjustBridge I = AdjustBridge._();

  bool _inited = false;

  /// 统一初始化入口：外部只要调用一次
  Future<String?> ensureInitialized({
    required String appToken,
    bool production = false,
    AdjustLogLevel logLevel = AdjustLogLevel.info,

    // 这些回调你可以不传，默认会 debugPrint + 写入 AdjustStore
    AdjustAttributionHandler? onAttribution,
    AdjustEventSuccessHandler? onEventSuccess,
    AdjustEventFailureHandler? onEventFailure,
    AdjustSessionSuccessHandler? onSessionSuccess,
    AdjustSessionFailureHandler? onSessionFailure,
  }) async {
    if (_inited) return "";
    _inited = true;

    final env = production
        ? AdjustEnvironment.production
        : AdjustEnvironment.sandbox;
    final config = AdjustConfig(appToken, env);
    config.logLevel = logLevel;
    config.attributionCallback = (AdjustAttribution a) {
      debugPrint("Adjust attribution: ${a.toString()}");
      SharedPreferences.getInstance().then(
        (prefs) => prefs.setString("adjustAttribution", a.jsonResponse ?? ""),
      );
      onAttribution?.call(a);
    };
    config.eventSuccessCallback = (AdjustEventSuccess s) {
      debugPrint("Adjust event success: ${s.toString()}");
      onEventSuccess?.call(s);
    };
    config.eventFailureCallback = (AdjustEventFailure f) {
      debugPrint("Adjust event failure: ${f.toString()}");
      onEventFailure?.call(f);
    };

    config.sessionSuccessCallback = (AdjustSessionSuccess s) {
      debugPrint("Adjust session success: ${s.toString()}");
      onSessionSuccess?.call(s);
    };
    config.sessionFailureCallback = (AdjustSessionFailure f) {
      debugPrint("Adjust session failure: ${f.toString()}");
      onSessionFailure?.call(f);
    };

    Adjust.initSdk(config);

    // 可选：启动后取一次 adid / attribution，存到 Store
    try {
      final adid = await Adjust.getAdid();
      debugPrint("Adjust adid: $adid");
      if (adid != null && adid.isNotEmpty) {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString("adjustAdId", adid);
      }
      return adid;
    } catch (_) {
      return null;
    }
  }

  /// 打普通事件
  void track(
    String eventToken, {
    Map<String, String>? callbackParams,
    Map<String, String>? partnerParams,
  }) {
    final e = AdjustEvent(eventToken);
    callbackParams?.forEach(e.addCallbackParameter);
    partnerParams?.forEach(e.addPartnerParameter);
    Adjust.trackEvent(e);
  }

  /// 打收入事件
  void revenue(
    String eventToken,
    double revenue,
    String currency,
    String? transactionId, { // 可选：防重复扣款（如果你使用）
    Map<String, String>? callbackParams,
    Map<String, String>? partnerParams,
  }) {
    final e = AdjustEvent(eventToken);
    e.setRevenue(revenue, currency);
    if (transactionId != null && transactionId.isNotEmpty) {
      e.deduplicationId = transactionId;
    }
    callbackParams?.forEach(e.addCallbackParameter);
    partnerParams?.forEach(e.addPartnerParameter);
    Adjust.trackEvent(e);
  }

  /// 关闭/开启 Adjust（例如用户拒绝隐私）
  Future<void> setEnabled(bool enabled) async {
    if (enabled) {
      Adjust.enable();
    } else {
      Adjust.disable();
    }
  }

  Future<bool> isEnabled() => Adjust.isEnabled();

  Future<String?> getAdid() => Adjust.getAdid();

  Future<AdjustAttribution?> getAttribution() => Adjust.getAttribution();
}
