import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/contribution.dart';
import '../../domain/repositories/contribution_repository.dart';
import '../../core/di/injection.dart';
import 'user_providers.dart';

/// 用户统计数据 - 来自贡献值服务
class UserStats {
  /// 是否已参与
  final bool hasAdopted;

  /// 引荐参与用户数
  final int directReferralAdoptedCount;

  /// 已解锁层级深度（可理解为团队层数）
  final int unlockedLevelDepth;

  /// 已解锁奖励档位数（VIP等级）
  final int unlockedBonusTiers;

  /// 总贡献值
  final String totalContribution;

  const UserStats({
    this.hasAdopted = false,
    this.directReferralAdoptedCount = 0,
    this.unlockedLevelDepth = 0,
    this.unlockedBonusTiers = 0,
    this.totalContribution = '0',
  });

  /// 从贡献值账户数据构建
  factory UserStats.fromContribution(Contribution contribution) {
    return UserStats(
      hasAdopted: contribution.hasAdopted,
      directReferralAdoptedCount: contribution.directReferralAdoptedCount,
      unlockedLevelDepth: contribution.unlockedLevelDepth,
      unlockedBonusTiers: contribution.unlockedBonusTiers,
      totalContribution: contribution.totalContribution,
    );
  }

  /// VIP等级显示
  String get vipLevel {
    if (unlockedBonusTiers <= 0) return '-';
    return 'V$unlockedBonusTiers';
  }

  /// 参与数量（简化展示引荐数）
  int get adoptionCount => hasAdopted ? 1 : 0;

  /// 团队人数估算（基于已解锁层级）
  int get teamSize {
    // 简单估算：每层平均3人
    if (unlockedLevelDepth <= 0) return 0;
    int total = 0;
    for (int i = 1; i <= unlockedLevelDepth; i++) {
      total += (directReferralAdoptedCount > 0 ? directReferralAdoptedCount : 1) * i;
    }
    return total;
  }
}

/// 用户统计数据 Provider
final userStatsProvider = FutureProvider<UserStats?>((ref) async {
  final user = ref.watch(userNotifierProvider);
  if (!user.isLoggedIn || user.accountSequence == null) {
    return null;
  }

  final repository = getIt<ContributionRepository>();
  final result = await repository.getUserContribution(user.accountSequence!);

  ref.keepAlive();
  final timer = Timer(const Duration(minutes: 5), () {
    ref.invalidateSelf();
  });
  ref.onDispose(() => timer.cancel());

  return result.fold(
    (failure) => const UserStats(),
    (contribution) => UserStats.fromContribution(contribution),
  );
});

/// 邀请码 Provider - 使用账户序号作为邀请码
final invitationCodeProvider = Provider<String>((ref) {
  final user = ref.watch(userNotifierProvider);
  return user.accountSequence ?? '--------';
});
