import 'dart:convert';

import 'package:adjust_sdk/adjust.dart';
import 'package:adjust_sdk/adjust_attribution.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'device_info.dart';
import 'http_util.dart';

const String _installSentKey = 'report_install_sent';
const String _attributionSentKey = 'report_attribution_sent';

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

  String adjustId = '';
  AdjustAttribution? _attribution;
  AdjustAttribution? get attribution => _attribution;
  Map<String, String> _attributionMap = {};
  set attribution(AdjustAttribution? a) {
    _attribution = a;
    _attributionMap = getAttributionMap();
  }

  void report(String eventName, Map<String, dynamic>? params) {
    sendReportAsync(eventName, params)
        .then((_) => debugPrint('Report sent successfully $eventName'))
        .catchError((error) {
          debugPrint('Failed to send report: $error');
        });
  }

  void reportInstall() {
    _sendDedupedReport(
      'install',
      _installSentKey,
      null,
    ).then((_) => debugPrint('Report install finished')).catchError((error) {
      debugPrint('Failed to send install report: $error');
    });
  }

  void reportAttribution() {
    if (_attribution == null) {
      debugPrint('Attribution data is null, skipping attribution report');
      return;
    }
    _sendDedupedReport('attribution', _attributionSentKey, {})
        .then((_) => debugPrint('Report attribution finished'))
        .catchError((error) {
          debugPrint('Failed to send attribution report: $error');
        });
  }

  Future<void> sendReportAsync(
    String eventName,
    Map<String, dynamic>? params,
  ) async {
    if (eventName.isEmpty) {
      debugPrint('Event name is empty, skipping report');
      return;
    }
    await _sendReport(eventName, params);
  }

  Future<void> _sendDedupedReport(
    String eventName,
    String sentKey,
    Map<String, dynamic>? params,
  ) async {
    final prefs = await SharedPreferences.getInstance();
    final alreadySent = prefs.getBool(sentKey) == true;
    if (alreadySent) {
      debugPrint('$eventName report already sent, skipping');
      return;
    }

    await _sendReport(eventName, params);
    await prefs.setBool(sentKey, true);
  }

  Future<void> _sendReport(
    String eventName,
    Map<String, dynamic>? params,
  ) async {
    final deviceInfo = await DeviceInfo.I.deviceInfo(includeAdjust: false);
    Map<String, dynamic> reportData = {
      'event': eventName,
      'params': params ?? {},
      'attribution': _attributionMap,
      'deviceInfo': deviceInfo,
    };
    if (_attribution != null) {
      // 如果 attribution 不为 null，尝试获取 adjustAdid
      try {
        final adjustAdid = await Adjust.getAdidWithTimeout(1000);
        reportData['adjustAdid'] = adjustAdid;
      } catch (e) {
        debugPrint('Failed to get Adjust Adid: $e');
      }
    }
    // 这里可以将 reportData 发送到服务器或者日志系统
    debugPrint('Report: $reportData');
    await reportInfo(jsonEncode(reportData));
  }

  Map<String, String> getAttributionMap() {
    if (_attribution == null) return {};
    return {
      'trackerToken': _attribution!.trackerToken ?? '',
      'trackerName': _attribution!.trackerName ?? '',
      'network': _attribution!.network ?? '',
      'campaign': _attribution!.campaign ?? '',
      'adgroup': _attribution!.adgroup ?? '',
      'creative': _attribution!.creative ?? '',
      'clickLabel': _attribution!.clickLabel ?? '',
      'costType': _attribution!.costType ?? '',
      'costAmount': _attribution!.costAmount?.toString() ?? '',
      'costCurrency': _attribution!.costCurrency ?? '',
      'jsonResponse': _attribution!.jsonResponse ?? '',
      'fbInstallReferrer': _attribution!.fbInstallReferrer ?? '',
    };
  }
}
