import 'dart:async';
import 'dart:io' show Platform;
import 'package:kaer_with_panels/app/services/kr_subscribe_service.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../services/api_service/kr_subscribe_api.dart';
import '../../../routes/app_pages.dart';
import '../../../model/response/kr_order_status.dart';
import '../../../utils/kr_event_bus.dart';
import '../../../utils/kr_common_util.dart';
import '../../../localization/app_translations.dart';
import '../../../utils/kr_log_util.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

/// 订单状态控制器（参考 Tauri 项目实现）
class KROrderStatusController extends GetxController with WidgetsBindingObserver {
  /// API服务
  final KRSubscribeApi kr_subscribeApi = KRSubscribeApi();
  final KRSubscribeService kr_subscribeService = KRSubscribeService();

  /// 支付是否成功
  final RxBool kr_isPaymentSuccess = false.obs;

  /// 是否正在加载
  final RxBool kr_isLoading = true.obs;

  final RxBool kr_isRefreshingData = false.obs;

  /// 支付URL
  final String kr_paymentUrl = Get.arguments['url'] as String? ?? '';

  /// 订单信息
  final String kr_order = Get.arguments['order'];

  /// 支付方式类型
  final String kr_paymentType = Get.arguments['payment_type'] as String;

  /// Checkout 类型（url, qr, stripe）
  final String kr_checkoutType = Get.arguments['checkout_type'] as String? ?? 'url';

  /// 定时器
  Timer? kr_timer;

  /// 倒计时定时器
  Timer? kr_countdownTimer;

  /// 15分钟倒计时（毫秒）
  final RxInt kr_countdown = (15 * 60 * 1000).obs;

  /// 格式化的倒计时字符串
  final RxString kr_formattedCountdown = '15:00'.obs;

  /// 订单创建时间（用于计算倒计时）
  DateTime? kr_orderCreatedAt;

  /// 上次刷新时间
  int kr_lastRefreshTime = 0;

  /// 订单状态常量
  static const int kr_statusPending = 1;    // 待支付
  static const int kr_statusPaid = 2;       // 已支付
  static const int kr_statusClose = 3;      // 已关闭
  static const int kr_statusFailed = 4;     // 支付失败
  static const int kr_statusFinished = 5;   // 已完成

  /// 状态标题
  final RxString kr_statusTitle = AppTranslations.kr_orderStatus.initialTitle.obs;

  /// 状态描述
  final RxString kr_statusDescription = AppTranslations.kr_orderStatus.initialDescription.obs;

  /// 状态图标名称
  final RxString kr_statusIcon = 'payment_success'.obs;

  @override
  void onInit() {
    super.onInit();
    if (kDebugMode) {
      print('═══════════════════════════════════════');
    }
    if (kDebugMode) {
      print('📊 订单状态页面初始化');
    }
    if (kDebugMode) {
      print('  订单号: $kr_order');
    }
    if (kDebugMode) {
      print('  支付方式: $kr_paymentType');
    }
    if (kDebugMode) {
      print('  Checkout类型: $kr_checkoutType');
    }
    if (kDebugMode) {
      print('═══════════════════════════════════════');
    }

    // 立即查询一次订单状态，获取创建时间
    kr_checkPaymentStatus();
    // 启动轮询和倒计时
    kr_startCheckingPaymentStatus();
    
    // 添加生命周期监听
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void onReady() {
    super.onReady();
    // 注意：支付链接已经在购买流程中打开了，这里不再重复打开
  }

  @override
  void onClose() {
    if (kDebugMode) {
      print('🔚 订单状态页面关闭，清理定时器');
    }
    kr_timer?.cancel();
    kr_countdownTimer?.cancel();
    // 移除生命周期监听
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (kDebugMode) {
        print('📱 App 恢复前台，立即更新倒计时和订单状态');
      }
      // 立即触发一次倒计时更新
      kr_updateCountdown();
      // 立即检查一次订单状态
      kr_checkPaymentStatus();
    }
  }

  /// 开始检查支付状态（参考 Tauri 项目：5秒轮询一次）
  void kr_startCheckingPaymentStatus() {
    if (kDebugMode) {
      print('🔄 启动支付状态轮询（每5秒检查一次）');
    }

    // 状态轮询：每5秒检查一次订单状态
    kr_timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      kr_checkPaymentStatus();
    });

    // 倒计时更新：每1秒更新一次UI显示
    kr_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      kr_updateCountdown();
    });
  }

  /// 更新倒计时（参考 Tauri 项目）
  void kr_updateCountdown() {
    if (kr_orderCreatedAt == null) {
      // 订单创建时间还未获取，显示默认倒计时
      kr_formattedCountdown.value = '15:00';
      if (kDebugMode) {
        print('⏱️ 倒计时更新: 等待订单创建时间...');
      }
      return;
    }

    final now = DateTime.now().millisecondsSinceEpoch;
    final createdAt = kr_orderCreatedAt!.millisecondsSinceEpoch;
    final targetTime = createdAt + (15 * 60 * 1000); // 15分钟后

    final timeLeft = targetTime - now;

    if (kDebugMode) {
      print('⏱️ 倒计时调试信息:');
    }
    if (kDebugMode) {
      print('  当前时间(ms): $now');
    }
    if (kDebugMode) {
      print('  创建时间(ms): $createdAt');
    }
    if (kDebugMode) {
      print('  目标时间(ms): $targetTime');
    }
    if (kDebugMode) {
      print('  剩余时间(ms): $timeLeft');
    }
    if (kDebugMode) {
      print('  剩余时间(秒): ${(timeLeft / 1000).floor()}');
    }

    if (timeLeft > 0) {
      kr_countdown.value = timeLeft;
      // 格式化倒计时：MM:SS
      final minutes = (timeLeft / 60000).floor();
      final seconds = ((timeLeft % 60000) / 1000).floor();
      kr_formattedCountdown.value = '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
      if (kDebugMode) {
        print('  格式化倒计时: ${kr_formattedCountdown.value}');
      }
    } else {
      // 倒计时结束，订单超时
      kr_countdown.value = 0;
      kr_formattedCountdown.value = '00:00';
      kr_countdownTimer?.cancel();
      kr_timer?.cancel();

      if (kDebugMode) {
        print('⏱️ 订单支付超时（15分钟）');
      }
      kr_statusTitle.value = AppTranslations.kr_orderStatus.closedTitle;
      kr_statusDescription.value = AppTranslations.kr_orderStatus.timeoutMessage;
      kr_isLoading.value = false;
    }
  }

  /// 检查支付状态（使用公开接口，参考 Tauri 项目）
  Future<void> kr_checkPaymentStatus() async {
    final now = DateTime.now().millisecondsSinceEpoch;

    try {
      if (kDebugMode) {
        print('🔍 检查订单状态 [${kr_order}]');
      }

      // 使用公开接口查询订单状态
      final result = await kr_subscribeApi.kr_queryOrderStatus(kr_order);

      // 注意：这里改为 async 回调以支持内部的 await
      await result.fold(
            (error) async {
          if (kDebugMode) {
            print('❌ 查询失败: ${error.msg}');
          }
          KRLogUtil.kr_e('检查支付状态失败: ${error.msg}', tag: 'OrderStatusController');
          kr_isLoading.value = false;
          kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;
          kr_statusDescription.value = AppTranslations.kr_orderStatus.checkFailedDescription;
        },
            (kr_orderStatus) async {
          // 1. 保存订单创建时间（用于倒计时）
          if (kr_orderCreatedAt == null && kr_orderStatus.kr_createdAt > 0) {
            final timestamp = kr_orderStatus.kr_createdAt;
            final isMilliseconds = timestamp > 10000000000;
            kr_orderCreatedAt = DateTime.fromMillisecondsSinceEpoch(
                isMilliseconds ? timestamp : timestamp * 1000
            );
          }

          if (kDebugMode) {
            print('📊 订单状态: ${kr_orderStatus.kr_status} (${_getStatusName(kr_orderStatus.kr_status)})');
          }

          // 2. 根据状态处理业务逻辑
          switch (kr_orderStatus.kr_status) {
            case kr_statusPending:
              kr_statusTitle.value = AppTranslations.kr_orderStatus.pendingTitle;
              kr_statusDescription.value = '${AppTranslations.kr_orderStatus.pendingDescription}\n${AppTranslations.kr_orderStatus.remainingTime}: ${kr_formattedCountdown.value}';
              kr_statusIcon.value = 'payment_success';
              break;

            case kr_statusPaid:
              if (kDebugMode) {
                print('✅ 订单已支付，等待确认...');
              }
              kr_statusTitle.value = AppTranslations.kr_orderStatus.paidTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.paidDescription;
              kr_statusIcon.value = 'payment_success';
              break;

            case kr_statusFinished:
            // 订单完成流程
              if (kDebugMode) {
                print('🎉 订单完成！停止轮询');
              }
              kr_isPaymentSuccess.value = true;
              kr_isLoading.value = false;

              // 停止所有定时器
              kr_timer?.cancel();
              kr_countdownTimer?.cancel();

              kr_statusTitle.value = AppTranslations.kr_orderStatus.successTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.successDescription;
              kr_statusIcon.value = 'payment_success';

              // 刷新订阅信息
              kr_isRefreshingData.value = true;
              try {
                await kr_subscribeService.kr_fetchAvailableSubscribes();
              } catch (e) {
                KRLogUtil.kr_e('刷新订阅信息异常: $e', tag: 'OrderStatusController');
              } finally {
                kr_isRefreshingData.value = false;
              }

              if (kDebugMode) {
                print('✅ [OrderStatus] 订单完成，数据已同步');
              }
              break;

            case kr_statusClose:
            case kr_statusFailed:
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_countdownTimer?.cancel();
              kr_statusTitle.value = kr_orderStatus.kr_status == kr_statusClose
                  ? AppTranslations.kr_orderStatus.closedTitle
                  : AppTranslations.kr_orderStatus.failedTitle;
              kr_statusDescription.value = kr_orderStatus.kr_status == kr_statusClose
                  ? AppTranslations.kr_orderStatus.closedDescription
                  : AppTranslations.kr_orderStatus.failedDescription;
              kr_statusIcon.value = 'payment_success';
              break;

            default:
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_countdownTimer?.cancel();
              kr_statusTitle.value = AppTranslations.kr_orderStatus.unknownTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.unknownDescription;
              break;
          }

          kr_lastRefreshTime = now;
        },
      );
    } catch (error) {
      if (kDebugMode) {
        print('❌ 异常: $error');
      }
      KRLogUtil.kr_e('检查支付状态程序异常: $error', tag: 'OrderStatusController');
      kr_isLoading.value = false;
      kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;
      kr_statusDescription.value = AppTranslations.kr_orderStatus.checkFailedDescription;
    }
  }

  /// 获取状态名称（用于日志）
  String _getStatusName(int status) {
    switch (status) {
      case kr_statusPending:
        return '待支付';
      case kr_statusPaid:
        return '已支付';
      case kr_statusClose:
        return '已关闭';
      case kr_statusFailed:
        return '支付失败';
      case kr_statusFinished:
        return '已完成';
      default:
        return '未知';
    }
  }

}
