import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_api.user.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/kr_dialog.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_auth_api.dart';
import 'package:kaer_with_panels/app/services/kr_site_config_service.dart';
import 'package:kaer_with_panels/app/services/kr_device_info_service.dart';
import 'package:kaer_with_panels/app/services/kr_subscribe_service.dart';
import 'package:kaer_with_panels/app/model/enum/kr_request_type.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'dart:io';
import 'dart:math';
import 'dart:convert';
import 'package:kaer_with_panels/utils/snackbar_util.dart';
import 'package:kaer_with_panels/app/routes/app_pages.dart';
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';

class HIUserInfoController extends GetxController {
  /// 订阅服务
  final KRSubscribeService kr_subscribeService = KRSubscribeService();

  // 设备列表
  final RxList<Map<String, dynamic>> devices = <Map<String, dynamic>>[].obs;

  // 加载状态
  final RxBool isLoading = true.obs;

  // 当前设备ID
  String? currentDeviceId;

  @override
  void onInit() {
    super.onInit();
    _initDeviceId();
    _initDeviceLimit();
    loadDeviceList();
  }

  /// 初始化当前设备ID
  Future<void> _initDeviceId() async {
    try {
      currentDeviceId = KRDeviceInfoService().deviceId ?? 'unknown';
      KRLogUtil.kr_i('当前设备ID: $currentDeviceId', tag: 'DeviceManagement');
    } catch (e) {
      KRLogUtil.kr_e('获取设备ID失败: $e', tag: 'DeviceManagement');
    }
  }

  /// 加载设备列表
  Future<void> loadDeviceList() async {
    try {
      isLoading.value = true;
      KRLogUtil.kr_i('开始加载设备列表', tag: 'DeviceManagement');

      // 调用API获取设备列表
      final result = await KRUserApi().kr_getUserDevices();

      result.fold(
        (error) {
          KRLogUtil.kr_e('加载设备列表失败: ${error.msg}', tag: 'DeviceManagement');
          KRSnackBarUtil.show(AppTranslations.kr_dialog.error, error.msg);
        },
        (deviceList) {
          KRLogUtil.kr_i('获取到 ${deviceList.length} 个设备',
              tag: 'DeviceManagement');

          // 转换设备数据格式
          devices.value = deviceList.map((device) {
            final identifier = device['identifier']?.toString() ?? '';
            final isCurrent = identifier == currentDeviceId;

            return {
              'id': device['id']?.toString() ?? '',
              'identifier': identifier,
              'device_name': device['user_agent'] ?? '未知设备',
              'ip': device['ip'] ?? '',
              'last_login': device['updated_at'] ?? device['created_at'] ?? '',
              'is_current': isCurrent,
              'enabled': device['enabled'] ?? true,
              'online': device['online'] ?? false,
            };
          }).toList()
            ..sort((a, b) {
              if (a['is_current'] == true) return -1;
              if (b['is_current'] == true) return 1;
              return 0;
            });
        },
      );
    } catch (e, stackTrace) {
      KRLogUtil.kr_e('加载设备列表异常: $e', tag: 'DeviceManagement');
      KRLogUtil.kr_e('堆栈跟踪: $stackTrace', tag: 'DeviceManagement');
      KRSnackBarUtil.show(AppTranslations.kr_dialog.error,
          AppTranslations.kr_deviceManagement.loadDeviceListFailed);
    } finally {
      isLoading.value = false;
    }
  }

  /// 删除设备
  Future<bool> deleteDevice(String id) async {
    try {
      final device = devices.firstWhere(
        (d) => d['id'] == id,
        orElse: () => {},
      );
      if (device.isEmpty) return false;

      final isCurrent = device['is_current'] ?? false;

      KRLogUtil.kr_i('开始解绑设备 - id: $id, isCurrent: $isCurrent',
          tag: 'DeviceManagement');

      final result = await KRUserApi().kr_unbindUserDevice(id);

      bool success = false;
      result.fold(
        (error) {
          KRLogUtil.kr_e('删除设备失败: ${error.msg}', tag: 'DeviceManagement');
          KRSnackBarUtil.show(AppTranslations.kr_dialog.error,
              AppTranslations.kr_deviceManagement.deleteFailed(error.msg));
        },
        (_) async {
          KRLogUtil.kr_i('设备删除成功', tag: 'DeviceManagement');
          success = true;

          if (isCurrent) {
            // 如果删除的是本机设备，重新进行设备登录
            KRLogUtil.kr_i('本机设备已删除，准备重新登录', tag: 'DeviceManagement');
            // 执行重新登录
            await _reloginWithDevice();
          } else {
            devices.removeWhere((device) => device['id'] == id);
            KRSnackBarUtil.show(AppTranslations.kr_dialog.success,
                AppTranslations.kr_deviceManagement.deleteSuccess);
          }
        },
      );

      return success;
    } catch (e, stackTrace) {
      KRLogUtil.kr_e('删除设备异常: $e', tag: 'DeviceManagement');
      KRLogUtil.kr_e('堆栈跟踪: $stackTrace', tag: 'DeviceManagement');
      KRSnackBarUtil.show(AppTranslations.kr_dialog.error,
          AppTranslations.kr_deviceManagement.deleteFailed(e.toString()));
      return false;
    }
  }

  /// 重新使用设备登录
  Future<void> _reloginWithDevice() async {
    try {
      KRLogUtil.kr_i('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
          tag: 'DeviceManagement');
      KRLogUtil.kr_i('开始重新进行设备登录', tag: 'DeviceManagement');
      KRLogUtil.kr_i('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
          tag: 'DeviceManagement');

      // 先清除当前的用户信息（但不调用 kr_loginOut，避免显示登录界面）
      final appRunData = KRAppRunData.getInstance();
      appRunData.kr_isLogin.value = false;
      appRunData.kr_token = null;
      appRunData.kr_account.value = null;
      appRunData.kr_userId.value = null;

      KRLogUtil.kr_i('设备登录已启用，开始调用设备登录接口', tag: 'DeviceManagement');

      // 初始化设备信息服务（如果还没初始化）
      await KRDeviceInfoService().initialize();

      // 调用设备登录接口
      final authApi = KRAuthApi();
      final result = await authApi.kr_deviceLogin();

      result.fold(
        (error) {
          // 设备登录失败
          KRLogUtil.kr_e('设备登录失败: ${error.msg}', tag: 'DeviceManagement');
          KRSnackBarUtil.show(AppTranslations.kr_dialog.error,
              AppTranslations.kr_deviceManagement.reloginFailed(error.msg));

          // 执行完整退出登录，显示登录界面
          appRunData.kr_loginOut();
        },
        (token) async {
          // 设备登录成功
          KRLogUtil.kr_i('✅ 设备登录成功！', tag: 'DeviceManagement');
          KRLogUtil.kr_i(
              '🎫 Token: ${token.substring(0, min(20, token.length))}...',
              tag: 'DeviceManagement');

          // 保存新的用户信息
          final deviceId = KRDeviceInfoService().deviceId ?? 'unknown';
          await appRunData.kr_saveUserInfo(
            token,
            'device_$deviceId',
          );

          KRLogUtil.kr_i('✅ 设备重新登录成功，已更新用户信息', tag: 'DeviceManagement');

          // 等待一小段时间，确保登录状态已经更新
          await Future.delayed(const Duration(milliseconds: 300));

          // 刷新订阅信息
          KRLogUtil.kr_i('🔄 开始刷新订阅信息...', tag: 'DeviceManagement');
          try {
            await KRSubscribeService().kr_refreshAll();
            KRLogUtil.kr_i('✅ 订阅信息刷新成功', tag: 'DeviceManagement');
          } catch (e) {
            KRLogUtil.kr_e('订阅信息刷新失败: $e', tag: 'DeviceManagement');
          }

          // KRSnackBarUtil.show(AppTranslations.kr_dialog.success, '退出登录成功');
          KRCommonUtil.kr_showToast('退出登录成功');
          Get.offAllNamed(Routes.KR_HOME);
        },
      );
    } catch (e, stackTrace) {
      KRLogUtil.kr_e('设备重新登录异常: $e', tag: 'DeviceManagement');
      KRLogUtil.kr_e('堆栈跟踪: $stackTrace', tag: 'DeviceManagement');
      KRSnackBarUtil.show(AppTranslations.kr_dialog.error,
          AppTranslations.kr_deviceManagement.reloginFailedGeneric);

      // 发生异常，执行完整退出登录
      await KRAppRunData.getInstance().kr_loginOut();
    }
  }

  Future<void> _initDeviceLimit() async {
    await KRSiteConfigService().fetchSiteConfig();
  }

  /// 获取设备类型和图标
  Map<String, dynamic> getDeviceTypeInfo(String userAgent) {
    String deviceType = AppTranslations.kr_deviceManagement.deviceTypeUnknown;
    String iconName = 'devices';

    if (userAgent.contains('Android') ||
        userAgent.toLowerCase().contains('android')) {
      deviceType =
          'Android'; // AppTranslations.kr_deviceManagement.deviceTypeAndroid;
      iconName = 'phone_android';
    } else if (userAgent.contains('iOS') ||
        userAgent.contains('iPhone') ||
        userAgent.toLowerCase().contains('ios')) {
      deviceType =
          'iPhone'; // AppTranslations.kr_deviceManagement.deviceTypeIos;
      iconName = 'phone_iphone';
    } else if (userAgent.contains('iPad')) {
      deviceType =
          'iPad'; // AppTranslations.kr_deviceManagement.deviceTypeIpad;
      iconName = 'tablet';
    } else if (userAgent.contains('macOS') ||
        userAgent.contains('Mac') ||
        userAgent.toLowerCase().contains('mac')) {
      deviceType =
          'Mac'; // AppTranslations.kr_deviceManagement.deviceTypeMacos;
      iconName = 'desktop_mac';
    } else if (userAgent.contains('Windows') ||
        userAgent.toLowerCase().contains('windows')) {
      deviceType =
          'Windows'; //AppTranslations.kr_deviceManagement.deviceTypeWindows;
      iconName = 'computer';
    } else if (userAgent.contains('Linux') ||
        userAgent.toLowerCase().contains('linux')) {
      deviceType =
          'Linux'; //AppTranslations.kr_deviceManagement.deviceTypeLinux;
      iconName = 'computer';
    }

    return {
      'type': deviceType,
      'icon': iconName,
    };
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
