import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';

import '../../pigeons/core_api.g.dart';
import '../../utils/haptic_feedback_manager.dart';
import '../../utils/log/logger.dart';
import '../constants/enums.dart';

class CoreController extends GetxService {
  final TAG = 'CoreController';

  final _state = ConnectionState.disconnected.obs;
  ConnectionState get state => _state.value;
  set state(ConnectionState value) => _state.value = value;

  // 事件流订阅
  StreamSubscription<String>? _eventSubscription;

  @override
  void onInit() {
    super.onInit();
    _initCheckConnect();
    _startListeningToEvents();
  }

  @override
  void onClose() {
    super.onClose();
    // 取消事件流订阅
    _eventSubscription?.cancel();
    _eventSubscription = null;
  }

  void _initCheckConnect() {
    CoreApi().isConnected().then((value) {
      if (value == true) {
        state = ConnectionState.connected;
        CoreApi().reconnect();
      } else {
        state = ConnectionState.disconnected;
      }
    });
  }

  void handleConnection() {
    if (state == ConnectionState.disconnected) {
      // 开始连接 - 轻微震动
      state = ConnectionState.connecting;
      HapticFeedbackManager.connectionStart();
      CoreApi().connect();
    } else {
      // 断开连接
      state = ConnectionState.disconnecting;
      HapticFeedbackManager.connectionDisconnected();
      CoreApi().disconnect();
    }
  }

  /// 开始监听来自 Android 的事件
  void _startListeningToEvents() {
    _eventSubscription = onEventChange().listen(
      _handleEventChange,
      onError: (error) {
        log(TAG, '事件流错误: $error');
      },
    );
  }

  /// 处理来自 Android 的事件变化
  void _handleEventChange(String event) {
    log(TAG, '收到事件: $event');

    if (event.startsWith('connecting')) {
      state = ConnectionState.connecting;
      HapticFeedbackManager.connectionStart();
    } else if (event.startsWith('connected')) {
      state = ConnectionState.connected;
      HapticFeedbackManager.connectionSuccess();
    } else if (event.startsWith('disconnecting')) {
      state = ConnectionState.disconnecting;
    } else if (event.startsWith('disconnected')) {
      state = ConnectionState.disconnected;
      HapticFeedbackManager.connectionDisconnected();
    } else if (event.startsWith('failed')) {
      state = ConnectionState.disconnected;
      HapticFeedbackManager.connectionDisconnected();
      // 可以显示错误提示
      Get.snackbar('连接失败', '无法建立连接，请重试');
    } else if (event.startsWith('permission_denied')) {
      state = ConnectionState.disconnected;
      HapticFeedbackManager.connectionDisconnected();
      // 可以显示错误提示
      Get.snackbar('权限拒绝', '无法建立连接，请重试');
    } else if (event.startsWith('stats_update:')) {
      _handleStatsUpdate(event);
    } else if (event.startsWith('delay_measured:')) {
      _handleDelayUpdate(event);
    } else if (event.startsWith('error:')) {
      _handleError(event);
    } else if (event.startsWith('service_status:')) {
      _handleServiceStatus(event);
    }
  }

  /// 处理统计信息更新
  void _handleStatsUpdate(String event) {
    try {
      final jsonStr = event.substring('stats_update:'.length);
      final stats = jsonDecode(jsonStr);
      stats['uplink'] ?? 0;
      stats['downlink'] ?? 0;
      // TODO: 处理统计信息更新
    } catch (e) {
      log(TAG, '解析统计信息失败: $e');
    }
  }

  /// 处理延迟更新
  void _handleDelayUpdate(String event) {
    try {
      event.substring('delay_measured:'.length);
      // TODO: 处理延迟更新
    } catch (e) {
      log(TAG, '解析延迟信息失败: $e');
    }
  }

  /// 处理错误信息
  void _handleError(String event) {
    final errorMessage = event.substring('error:'.length);
    Get.snackbar('错误', errorMessage);
  }

  /// 处理服务状态
  void _handleServiceStatus(String event) {
    final status = event.substring('service_status:'.length);
    log(TAG, '服务状态: $status');
  }
}
