import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flashlink/app/components/ix_snackbar.dart';

import '../../../../config/translations/strings_enum.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: Strings.currentDevice.tr,
        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) {
      // 检查设备数量限制
      if (currentDevices.length >= maxDevices) {
        IXSnackBar.showIXErrorSnackBar(
          title: Strings.deviceLimitReached.tr,
          message:
              '${Strings.deviceLimitMessage.tr} $maxDevices ${Strings.devices.tr}',
        );
        inputCode.value = '';
        isCodeComplete.value = false;
        return;
      }

      isAuthorizing.value = true;
      authorizationStatus.value = AuthorizationStatus.configuring;

      // 模拟授权过程（实际应该调用API）
      Timer(const Duration(seconds: 2), () {
        isAuthorizing.value = false;
        authorizationStatus.value = AuthorizationStatus.success;

        // 添加新设备
        final newId = (currentDevices.length + 1).toString();
        currentDevices.add(
          DeviceInfo(
            id: newId,
            name: Strings.androidDevices.tr,
            type: DeviceTypeEnum.android,
            uid: 'UID 123-456-789-10$newId',
            date: _getCurrentDateTime(),
            isCurrent: false,
          ),
        );

        // 显示成功提示
        IXSnackBar.showIXSnackBar(
          title: Strings.deviceAuthorized.tr,
          message: Strings.deviceAuthorizedMessage.tr,
        );

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

        // 重置状态
        Timer(const Duration(milliseconds: 500), () {
          authorizationStatus.value = AuthorizationStatus.waiting;
        });
      });
    }
  }

  /// 获取当前日期时间
  String _getCurrentDateTime() {
    final now = DateTime.now();
    return '${now.year}/${now.month.toString().padLeft(2, '0')}/${now.day.toString().padLeft(2, '0')} '
        '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
  }

  /// 移除设备
  void removeDevice(String deviceId) {
    final device = currentDevices.firstWhere((d) => d.id == deviceId);

    Get.dialog(
      AlertDialog(
        title: Text(Strings.relieveDevice.tr),
        content: Text(
          '${Strings.relieveDeviceMessage.tr} ${device.name}?\n\n'
          '${Strings.relieveDeviceLoseAccess.tr}',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(Strings.cancel.tr),
          ),
          TextButton(
            onPressed: () {
              currentDevices.removeWhere((d) => d.id == deviceId);
              Get.back();
              Get.snackbar(
                Strings.deviceRelieved.tr,
                '${device.name} ${Strings.deviceRelievedMessage.tr}',
                snackPosition: SnackPosition.bottom,
              );
            },
            child: Text(
              Strings.relieveDevice.tr,
              style: const TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  /// 复制授权码
  void copyAuthCode() {
    // TODO: 实现复制到剪贴板
    IXSnackBar.showIXSnackBar(
      title: Strings.copied.tr,
      message: Strings.authCodeCopied.tr,
    );
  }

  /// 获取倒计时显示文本
  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 }
