import 'dart:async';
import 'package:get/get.dart';

class DeviceauthController extends GetxController {
  // 用户类型：true为VIP用户，false为免费用户
  final isPremium = true.obs;

  // 授权码相关
  final authCode = '673999'.obs;
  final countdownSeconds = 899.obs; // 15分钟 = 900秒，从899开始倒计时
  Timer? _countdownTimer;

  // 输入码相关
  final inputCode = ''.obs;
  final isCodeComplete = false.obs;
  final isAuthorizing = false.obs;

  // 设备管理
  final currentDevices = <DeviceInfo>[].obs;
  final maxDevices = 4;

  // 授权状态
  final authorizationStatus = AuthorizationStatus.waiting.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeDevices();
    _startCountdown();
  }

  @override
  void onClose() {
    _countdownTimer?.cancel();
    super.onClose();
  }

  /// 初始化设备列表
  void _initializeDevices() {
    currentDevices.add(
      DeviceInfo(
        id: '1',
        name: 'Current Device',
        type: DeviceTypeEnum.ios,
        date: '2022/01/25 13:45',
        isCurrent: true,
      ),
    );
  }

  /// 开始倒计时
  void _startCountdown() {
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdownSeconds.value > 0) {
        countdownSeconds.value--;
      } else {
        // 倒计时结束，刷新授权码
        _refreshAuthCode();
        countdownSeconds.value = 899;
      }
    });
  }

  /// 刷新授权码
  void _refreshAuthCode() {
    // 生成新的6位随机码
    final random = DateTime.now().millisecondsSinceEpoch;
    authCode.value = (random % 900000 + 100000).toString();
  }

  /// 设置输入码（由pinput调用）
  void setInputCode(String code) {
    inputCode.value = code;
    isCodeComplete.value = code.length == 6;
  }

  /// 提交授权码
  void submitAuthCode() {
    if (inputCode.value.length == 6) {
      isAuthorizing.value = true;
      authorizationStatus.value = AuthorizationStatus.configuring;

      // 模拟授权过程
      Timer(const Duration(seconds: 2), () {
        isAuthorizing.value = false;
        authorizationStatus.value = AuthorizationStatus.success;

        // 添加新设备
        currentDevices.add(
          DeviceInfo(
            id: '2',
            name: 'Android devices',
            type: DeviceTypeEnum.android,
            uid: 'UID 123-456-789-101',
            isCurrent: false,
          ),
        );

        // 清空输入码
        inputCode.value = '';
        isCodeComplete.value = false;
      });
    }
  }

  /// 移除设备
  void removeDevice(String deviceId) {
    currentDevices.removeWhere((device) => device.id == deviceId);
  }

  /// 复制授权码
  void copyAuthCode() {
    // TODO: 实现复制到剪贴板
    Get.snackbar('已复制', '授权码已复制到剪贴板');
  }

  /// 获取倒计时显示文本
  String get countdownText {
    final minutes = countdownSeconds.value ~/ 60;
    final seconds = countdownSeconds.value % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  /// 获取当前设备数量
  int get currentDeviceCount => currentDevices.length;

  /// 获取设备数量显示文本
  String get deviceCountText => '$currentDeviceCount/$maxDevices';
}

/// 设备信息类
class DeviceInfo {
  final String id;
  final String name;
  final DeviceTypeEnum type;
  final String? uid;
  final String? date;
  final bool isCurrent;

  DeviceInfo({
    required this.id,
    required this.name,
    required this.type,
    this.uid,
    this.date,
    this.isCurrent = false,
  });
}

/// 设备类型枚举
enum DeviceTypeEnum { ios, android, windows, mac }

/// 授权状态枚举
enum AuthorizationStatus { waiting, configuring, success, failed }
