import 'package:get/get.dart';
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_api.user.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/routes/app_pages.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';

/// 邀请进度状态
class KRInviteProgress {
  final int pending;
  final int processing;
  final int success;
  final int expired;
  final int registers;
  final int totalCommission;

  KRInviteProgress({
    this.pending = 0,
    this.processing = 0,
    this.success = 0,
    this.expired = 0,
    this.registers = 0,
    this.totalCommission = 0,
  });
}

class KRInviteController extends GetxController {
  final kr_progress = KRInviteProgress(
    pending: 0,
    processing: 0,
    success: 0,
    expired: 0,
    registers: 0,
    totalCommission: 0,
  ).obs;
  final kr_referCode = ''.obs;
  final kr_refererId = 0.obs;
  final kr_isLoading = false.obs;
  final count = 0.obs;
  final EasyRefreshController refreshController = EasyRefreshController();
  final otherInviteCodeController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    ever(KRAppRunData.getInstance().kr_isLogin, (value) {
      if (value) {
        _kr_fetchUserInfo();
        _kr_fetchAffiliateCount();
      } else {
        kr_progress.value = KRInviteProgress(
          pending: 0,
          processing: 0,
          success: 0,
          expired: 0,
          registers: 0,
          totalCommission: 0,
        );
        kr_referCode.value = '';
        kr_refererId.value = 0;
      }
    });
    if (KRAppRunData.getInstance().kr_isLogin.value) {
      _kr_fetchUserInfo();
      _kr_fetchAffiliateCount();
    }
  }

  // ⚠️ 已废弃：新版本后端不再提供 kr_getUserInfo 接口
  // 从 AppRunData 获取邀请码（登录后自动获取）
  Future<void> _kr_fetchUserInfo() async {
    try {
      kr_isLoading.value = true;

      KRLogUtil.kr_i('🔍 [InviteController] 开始获取邀请码...', tag: 'InviteController');

      // 从 AppRunData 获取用户邀请码（已在登录时获取）
      final appData = KRAppRunData.getInstance();
      KRLogUtil.kr_i('📊 [InviteController] AppRunData 状态:', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_isLogin: ${appData.kr_isLogin.value}', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_account: ${appData.kr_account.value}', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_referCode: ${appData.kr_referCode.value}', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_refererId: ${appData.kr_refererId.value}', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_balance: ${appData.kr_balance.value}', tag: 'InviteController');
      KRLogUtil.kr_i('  - kr_commission: ${appData.kr_commission.value}', tag: 'InviteController');

      kr_referCode.value = appData.kr_referCode.value;
      kr_refererId.value = appData.kr_refererId.value;
      KRLogUtil.kr_i('📋 [InviteController] 获取到邀请码: "${kr_referCode.value}"', tag: 'InviteController');
      KRLogUtil.kr_i('📋 [InviteController] 获取到邀请人ID: ${kr_refererId.value}', tag: 'InviteController');

      if (kr_referCode.value.isEmpty) {
        KRLogUtil.kr_w('⚠️ [InviteController] 邀请码为空！', tag: 'InviteController');
      }

    } catch (e) {
      KRLogUtil.kr_e('❌ [InviteController] 获取邀请码失败: $e', tag: 'InviteController');
      KRCommonUtil.kr_showToast(e.toString());
    } finally {
      kr_isLoading.value = false;
    }
  }

  Future<bool> kr_checkLoginStatus() async {
    return KRAppRunData.getInstance().kr_isLogin.value;
  }

  /// 获取分享链接
  String kr_getShareLink() {
    if (kr_referCode.isEmpty) {
      return '';
    }
    return '${AppConfig.getInstance().kr_invitation_link}${kr_referCode.value}';
  }

  /// 获取二维码内容
  String kr_getQRCodeContent() {
    return kr_getShareLink();
  }

  /// 复制文本到剪贴板
  Future<void> _kr_copyToClipboard(String text) async {
    await Clipboard.setData(ClipboardData(text: text));
    KRCommonUtil.kr_showToast(AppTranslations.kr_invite.copiedToClipboard);
  }

  void kr_viewRewardDetails() {
    // TODO: 实现查看奖励明细功能
  }

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

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

  void increment() => count.value++;

  /// 处理绑定邀请码
  Future<void> kr_handleBindInviteCode() async {
    final text = otherInviteCodeController.text.trim();
    if (text.isEmpty) {
      KRCommonUtil.kr_showToast('请输入邀请码');
      return;
    }
    if (text.trim().toLowerCase() == kr_referCode.value.trim().toLowerCase()) {
      KRCommonUtil.kr_showToast('您不可以邀请自己');
      return;
    }

    try {
      final either = await KRUserApi().hi_inviteCode(text);
      either.fold(
            (error) => KRCommonUtil.kr_showToast(error.msg),
            (success) {
              KRCommonUtil.kr_showToast('绑定成功: $text');
              otherInviteCodeController.text = '';
              _kr_fetchUserInfo(); // 刷新用户信息以更新 refererId 并隐藏输入框
            },
      );
    } catch (e) {
      KRCommonUtil.kr_showToast(e.toString());
    }

  }

  /// 获取邀请统计信息
  Future<void> _kr_fetchAffiliateCount() async {
    try {
      final either = await KRUserApi().kr_getAffiliateCount();
      either.fold(
        (error) => KRCommonUtil.kr_showToast(error.msg),
        (affiliateCount) {
          kr_progress.value = KRInviteProgress(
            pending: kr_progress.value.pending,
            processing: kr_progress.value.processing,
            success: kr_progress.value.success,
            expired: kr_progress.value.expired,
            registers: affiliateCount.registers,
            totalCommission: affiliateCount.totalCommission,
          );
        },
      );
    } catch (e) {
      KRCommonUtil.kr_showToast(e.toString());
    }
  }

  Future<void> kr_onRefresh() async {
    if (!KRAppRunData.getInstance().kr_isLogin.value) {
      refreshController.finishRefresh();
      return;
    }
    
    try {
      await _kr_fetchUserInfo();
      await _kr_fetchAffiliateCount();
    } finally {
      refreshController.finishRefresh();
    }
  }
}

