import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/account_service.dart';
import '../../../../core/storage/secure_storage.dart';
import '../../../../core/storage/storage_keys.dart';

/// 钱包状态枚举
enum WalletGenerationStatus {
  unknown, // 未知状态
  generating, // 生成中
  ready, // 已就绪
}

/// 钱包状态信息
class WalletStatusState {
  final WalletGenerationStatus status;
  final DateTime? lastChecked;
  final bool isPolling;

  const WalletStatusState({
    this.status = WalletGenerationStatus.unknown,
    this.lastChecked,
    this.isPolling = false,
  });

  WalletStatusState copyWith({
    WalletGenerationStatus? status,
    DateTime? lastChecked,
    bool? isPolling,
  }) {
    return WalletStatusState(
      status: status ?? this.status,
      lastChecked: lastChecked ?? this.lastChecked,
      isPolling: isPolling ?? this.isPolling,
    );
  }

  bool get isGenerating => status == WalletGenerationStatus.generating;
  bool get isReady => status == WalletGenerationStatus.ready;
}

/// 钱包状态管理器
///
/// 设计原则：只要钱包不是 ready 状态，就持续轮询并自动重试生成
/// - 轮询间隔：1-10分钟（幂等）
/// - 只有 ready 时停止轮询
/// - 非 ready 时自动调用 retryWalletGeneration API 触发新的生成过程
class WalletStatusNotifier extends StateNotifier<WalletStatusState> {
  final AccountService _accountService;
  final SecureStorage _secureStorage;
  Timer? _pollingTimer;

  WalletStatusNotifier(this._accountService, this._secureStorage)
      : super(const WalletStatusState());

  /// 开始轮询钱包状态
  ///
  /// 每60秒检查一次，直到钱包就绪
  Future<void> startPolling() async {
    if (state.isPolling) {
      debugPrint('[WalletStatusProvider] Already polling, skipping');
      return;
    }

    // 先从本地存储读取钱包状态
    final isWalletReady = await _secureStorage.read(key: StorageKeys.isWalletReady);
    if (isWalletReady == 'true') {
      // 本地已标记为 ready，直接设置状态，不需要轮询
      debugPrint('[WalletStatusProvider] Local storage shows wallet ready, skip polling');
      state = state.copyWith(
        status: WalletGenerationStatus.ready,
        lastChecked: DateTime.now(),
      );
      return;
    }

    debugPrint('[WalletStatusProvider] Starting wallet status polling');
    state = state.copyWith(isPolling: true);

    // 立即检查一次
    await _checkAndRetryIfNeeded();

    // 设置定时器，每60秒检查一次（幂等，1-10分钟间隔）
    _pollingTimer?.cancel();
    _pollingTimer = Timer.periodic(const Duration(seconds: 60), (_) async {
      await _checkAndRetryIfNeeded();
    });
  }

  /// 停止轮询
  void stopPolling() {
    debugPrint('[WalletStatusProvider] Stopping wallet status polling');
    _pollingTimer?.cancel();
    _pollingTimer = null;
    state = state.copyWith(isPolling: false);
  }

  /// 检查钱包状态，非 ready 时自动重试
  Future<void> _checkAndRetryIfNeeded() async {
    try {
      debugPrint('[WalletStatusProvider] Checking wallet status...');

      // 获取用户序列号
      final userSerialNum =
          await _secureStorage.read(key: StorageKeys.userSerialNum);
      if (userSerialNum == null) {
        debugPrint(
            '[WalletStatusProvider] No userSerialNum found, stopping polling');
        stopPolling();
        return;
      }

      // 调用 API 获取钱包状态
      final walletInfo = await _accountService.getWalletInfo(userSerialNum);

      debugPrint(
          '[WalletStatusProvider] Wallet status: ${walletInfo.status}');

      if (walletInfo.isReady) {
        // 钱包已就绪，保存标记并停止轮询
        await _secureStorage.write(
          key: StorageKeys.isWalletReady,
          value: 'true',
        );
        debugPrint('[WalletStatusProvider] Wallet is ready, stopping polling');

        state = state.copyWith(
          status: WalletGenerationStatus.ready,
          lastChecked: DateTime.now(),
        );

        stopPolling();
      } else if (walletInfo.isFailed) {
        // 只有失败状态才触发重试，生成中状态不重试
        debugPrint('[WalletStatusProvider] Wallet generation failed, triggering retry...');

        try {
          await _accountService.retryWalletGeneration();
          debugPrint('[WalletStatusProvider] Retry triggered successfully');
        } catch (e) {
          debugPrint('[WalletStatusProvider] Retry API call failed: $e');
          // 继续轮询，下次再试
        }

        state = state.copyWith(
          status: WalletGenerationStatus.generating,
          lastChecked: DateTime.now(),
        );
      } else {
        // 生成中状态，只更新状态，继续轮询等待完成
        debugPrint('[WalletStatusProvider] Wallet is generating, waiting...');

        state = state.copyWith(
          status: WalletGenerationStatus.generating,
          lastChecked: DateTime.now(),
        );
      }
    } catch (e) {
      debugPrint('[WalletStatusProvider] Error checking wallet status: $e');
      // 出错不停止轮询，继续尝试
      state = state.copyWith(
        lastChecked: DateTime.now(),
      );
    }
  }

  @override
  void dispose() {
    _pollingTimer?.cancel();
    super.dispose();
  }
}

/// 钱包状态 Provider
final walletStatusProvider =
    StateNotifierProvider<WalletStatusNotifier, WalletStatusState>((ref) {
  final accountService = ref.watch(accountServiceProvider);
  final secureStorage = ref.watch(secureStorageProvider);
  return WalletStatusNotifier(accountService, secureStorage);
});
