import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import 'telemetry_event.dart';
import '../presence/presence_config.dart';

class TelemetryConfig {
  bool globalEnabled = true;
  bool errorReportEnabled = true;
  bool performanceEnabled = true;
  bool userActionEnabled = true;
  bool pageViewEnabled = true;
  bool sessionEnabled = true;
  double samplingRate = 0.1;
  List<String> disabledEvents = [];
  String configVersion = '1.0.0';
  bool userOptIn = true;
  PresenceConfig? presenceConfig;

  static final TelemetryConfig _instance = TelemetryConfig._();
  TelemetryConfig._();
  factory TelemetryConfig() => _instance;

  Future<void> syncFromRemote(String apiBaseUrl) async {
    try {
      final dio = Dio(BaseOptions(
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 5),
      ));
      final response = await dio.get('$apiBaseUrl/telemetry/config');
      final data = response.data as Map<String, dynamic>;

      globalEnabled = data['global_enabled'] ?? true;
      errorReportEnabled = data['error_report_enabled'] ?? true;
      performanceEnabled = data['performance_enabled'] ?? true;
      userActionEnabled = data['user_action_enabled'] ?? true;
      pageViewEnabled = data['page_view_enabled'] ?? true;
      sessionEnabled = data['session_enabled'] ?? true;
      samplingRate = (data['sampling_rate'] ?? 0.1).toDouble();
      disabledEvents = List<String>.from(data['disabled_events'] ?? []);
      configVersion = data['version'] ?? '1.0.0';

      if (data['presence_config'] != null) {
        presenceConfig = PresenceConfig.fromJson(data['presence_config']);
      }

      await _saveToLocal();
    } catch (e) {
      debugPrint('[TelemetryConfig] Remote sync failed (non-blocking): $e');
      await _loadFromLocal();
    }
  }

  Future<void> _saveToLocal() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('telemetry_global_enabled', globalEnabled);
    await prefs.setBool('telemetry_error_enabled', errorReportEnabled);
    await prefs.setBool('telemetry_performance_enabled', performanceEnabled);
    await prefs.setBool('telemetry_user_action_enabled', userActionEnabled);
    await prefs.setBool('telemetry_page_view_enabled', pageViewEnabled);
    await prefs.setBool('telemetry_session_enabled', sessionEnabled);
    await prefs.setDouble('telemetry_sampling_rate', samplingRate);
    await prefs.setStringList('telemetry_disabled_events', disabledEvents);
    await prefs.setString('telemetry_config_version', configVersion);
  }

  Future<void> _loadFromLocal() async {
    final prefs = await SharedPreferences.getInstance();
    globalEnabled = prefs.getBool('telemetry_global_enabled') ?? true;
    errorReportEnabled = prefs.getBool('telemetry_error_enabled') ?? true;
    performanceEnabled = prefs.getBool('telemetry_performance_enabled') ?? true;
    userActionEnabled = prefs.getBool('telemetry_user_action_enabled') ?? true;
    pageViewEnabled = prefs.getBool('telemetry_page_view_enabled') ?? true;
    sessionEnabled = prefs.getBool('telemetry_session_enabled') ?? true;
    samplingRate = prefs.getDouble('telemetry_sampling_rate') ?? 0.1;
    disabledEvents = prefs.getStringList('telemetry_disabled_events') ?? [];
    configVersion = prefs.getString('telemetry_config_version') ?? '1.0.0';
  }

  bool shouldLog(EventType type, String eventName) {
    if (!globalEnabled) return false;
    if (!userOptIn) return false;
    if (disabledEvents.contains(eventName)) return false;

    switch (type) {
      case EventType.error:
      case EventType.crash:
        return errorReportEnabled;
      case EventType.performance:
        return performanceEnabled;
      case EventType.userAction:
        return userActionEnabled;
      case EventType.pageView:
        return pageViewEnabled;
      case EventType.apiCall:
        return performanceEnabled;
      case EventType.session:
        return sessionEnabled;
      case EventType.presence:
        return presenceConfig?.enabled ?? true;
    }
  }

  Future<void> setUserOptIn(bool optIn) async {
    userOptIn = optIn;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('telemetry_user_opt_in', optIn);
  }

  Future<void> loadUserOptIn() async {
    final prefs = await SharedPreferences.getInstance();
    userOptIn = prefs.getBool('telemetry_user_opt_in') ?? true;
  }
}
