import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../constants/api_endpoints.dart';

/// 推荐信息响应 (来自 referral-service)
class ReferralInfoResponse {
  final String userId;
  final String referralCode;
  final String? referrerId;
  final int referralChainDepth;
  final int directReferralCount;
  final int totalTeamCount;
  final int personalPlantingCount;
  final int teamPlantingCount;
  final double leaderboardScore;
  final int? leaderboardRank;
  final DateTime createdAt;

  ReferralInfoResponse({
    required this.userId,
    required this.referralCode,
    this.referrerId,
    required this.referralChainDepth,
    required this.directReferralCount,
    required this.totalTeamCount,
    required this.personalPlantingCount,
    required this.teamPlantingCount,
    required this.leaderboardScore,
    this.leaderboardRank,
    required this.createdAt,
  });

  factory ReferralInfoResponse.fromJson(Map<String, dynamic> json) {
    return ReferralInfoResponse(
      userId: json['userId']?.toString() ?? '',
      referralCode: json['referralCode'] ?? '',
      referrerId: json['referrerId']?.toString(),
      referralChainDepth: json['referralChainDepth'] ?? 0,
      directReferralCount: json['directReferralCount'] ?? 0,
      totalTeamCount: json['totalTeamCount'] ?? 0,
      personalPlantingCount: json['personalPlantingCount'] ?? 0,
      teamPlantingCount: json['teamPlantingCount'] ?? 0,
      leaderboardScore: (json['leaderboardScore'] ?? 0).toDouble(),
      leaderboardRank: json['leaderboardRank'],
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
    );
  }
}

/// 直推成员信息
class DirectReferralInfo {
  final String userId;
  final String accountSequence;  // 账户序列号（新格式: D + YYMMDD + 5位序号），用于显示
  final String referralCode;
  final int personalPlantingCount;  // 个人认种量
  final int teamPlantingCount;      // 团队认种量
  final int directReferralCount;    // 直推人数（用于判断是否有下级）
  final DateTime joinedAt;

  DirectReferralInfo({
    required this.userId,
    required this.accountSequence,
    required this.referralCode,
    required this.personalPlantingCount,
    required this.teamPlantingCount,
    required this.directReferralCount,
    required this.joinedAt,
  });

  factory DirectReferralInfo.fromJson(Map<String, dynamic> json) {
    return DirectReferralInfo(
      userId: json['userId']?.toString() ?? '',
      accountSequence: json['accountSequence']?.toString() ?? '',
      referralCode: json['referralCode'] ?? '',
      personalPlantingCount: json['personalPlantingCount'] ?? 0,
      teamPlantingCount: json['teamPlantingCount'] ?? 0,
      directReferralCount: json['directReferralCount'] ?? 0,
      joinedAt: json['joinedAt'] != null
          ? DateTime.parse(json['joinedAt'])
          : DateTime.now(),
    );
  }
}

/// 直推列表响应
class DirectReferralsResponse {
  final List<DirectReferralInfo> referrals;
  final int total;
  final bool hasMore;

  DirectReferralsResponse({
    required this.referrals,
    required this.total,
    required this.hasMore,
  });

  factory DirectReferralsResponse.fromJson(Map<String, dynamic> json) {
    return DirectReferralsResponse(
      referrals: (json['referrals'] as List? ?? [])
          .map((e) => DirectReferralInfo.fromJson(e))
          .toList(),
      total: json['total'] ?? 0,
      hasMore: json['hasMore'] ?? false,
    );
  }
}

/// 推荐链接响应
class ReferralLinkResponse {
  final String linkId;
  final String referralCode;
  final String shortUrl;
  final String fullUrl;
  final String downloadUrl;  // APK 下载链接
  final String? channel;
  final String? campaignId;
  final DateTime createdAt;

  ReferralLinkResponse({
    required this.linkId,
    required this.referralCode,
    required this.shortUrl,
    required this.fullUrl,
    required this.downloadUrl,
    this.channel,
    this.campaignId,
    required this.createdAt,
  });

  factory ReferralLinkResponse.fromJson(Map<String, dynamic> json) {
    return ReferralLinkResponse(
      linkId: json['linkId'] ?? '',
      referralCode: json['referralCode'] ?? '',
      shortUrl: json['shortUrl'] ?? '',
      fullUrl: json['fullUrl'] ?? '',
      downloadUrl: json['downloadUrl'] ?? 'https://s3.szaiai.com/rwadurian/app-release.apk',
      channel: json['channel'],
      campaignId: json['campaignId'],
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
    );
  }
}

/// 用户信息响应 (含推荐链接)
class MeResponse {
  final String userId;
  final String accountSequence;
  final String? phoneNumber;
  final String nickname;
  final String? avatarUrl;
  final String referralCode;
  final String referralLink;
  final List<WalletAddress> walletAddresses;
  final String kycStatus;
  final String status;
  final DateTime registeredAt;

  MeResponse({
    required this.userId,
    required this.accountSequence,
    this.phoneNumber,
    required this.nickname,
    this.avatarUrl,
    required this.referralCode,
    required this.referralLink,
    required this.walletAddresses,
    required this.kycStatus,
    required this.status,
    required this.registeredAt,
  });

  factory MeResponse.fromJson(Map<String, dynamic> json) {
    return MeResponse(
      userId: json['userId'] ?? '',
      accountSequence: json['accountSequence']?.toString() ?? '',
      phoneNumber: json['phoneNumber'],
      nickname: json['nickname'] ?? '',
      avatarUrl: json['avatarUrl'],
      referralCode: json['referralCode'] ?? '',
      referralLink: json['referralLink'] ?? '',
      walletAddresses: (json['walletAddresses'] as List? ?? [])
          .map((e) => WalletAddress.fromJson(e))
          .toList(),
      kycStatus: json['kycStatus'] ?? 'NONE',
      status: json['status'] ?? 'ACTIVE',
      registeredAt: json['registeredAt'] != null
          ? DateTime.parse(json['registeredAt'])
          : DateTime.now(),
    );
  }
}

class WalletAddress {
  final String chainType;
  final String address;

  WalletAddress({required this.chainType, required this.address});

  factory WalletAddress.fromJson(Map<String, dynamic> json) {
    return WalletAddress(
      chainType: json['chainType'] ?? '',
      address: json['address'] ?? '',
    );
  }
}

/// 推荐服务
///
/// 处理推荐链接相关功能:
/// - 获取用户信息和默认推荐链接
/// - 生成渠道专属推荐链接 (短链)
/// - 获取推荐关系信息
class ReferralService {
  final ApiClient _apiClient;

  ReferralService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 获取当前用户信息 (包含默认推荐链接)
  ///
  /// 调用 GET /me (identity-service)
  Future<MeResponse> getMe() async {
    try {
      debugPrint('获取用户信息...');
      final response = await _apiClient.get(ApiEndpoints.me);

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('用户信息获取成功: referralLink=${data['referralLink']}');
        return MeResponse.fromJson(data);
      }

      throw Exception('获取用户信息失败');
    } catch (e) {
      debugPrint('获取用户信息失败: $e');
      rethrow;
    }
  }

  /// 获取当前用户推荐信息
  ///
  /// 调用 GET /referral/me (referral-service)
  Future<ReferralInfoResponse> getMyReferralInfo() async {
    try {
      debugPrint('获取推荐信息...');
      final response = await _apiClient.get(ApiEndpoints.referralMe);

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('推荐信息获取成功: directReferralCount=${data['directReferralCount']}');
        return ReferralInfoResponse.fromJson(data);
      }

      throw Exception('获取推荐信息失败');
    } catch (e) {
      debugPrint('获取推荐信息失败: $e');
      rethrow;
    }
  }

  /// 获取直推列表
  ///
  /// 调用 GET /referral/me/direct-referrals (referral-service)
  Future<DirectReferralsResponse> getDirectReferrals({
    int limit = 50,
    int offset = 0,
  }) async {
    try {
      debugPrint('获取直推列表...');
      final response = await _apiClient.get(
        ApiEndpoints.referralDirects,
        queryParameters: {
          'limit': limit,
          'offset': offset,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('直推列表获取成功: total=${data['total']}');
        return DirectReferralsResponse.fromJson(data);
      }

      throw Exception('获取直推列表失败');
    } catch (e) {
      debugPrint('获取直推列表失败: $e');
      rethrow;
    }
  }

  /// 生成推荐链接 (短链)
  ///
  /// 调用 POST /referrals/links
  /// 返回包含 shortUrl 和 fullUrl 的响应
  ///
  /// [channel] - 渠道标识: wechat, telegram, twitter 等
  /// [campaignId] - 活动ID (可选)
  Future<ReferralLinkResponse> generateReferralLink({
    String? channel,
    String? campaignId,
  }) async {
    try {
      debugPrint('生成推荐链接: channel=$channel, campaignId=$campaignId');

      final response = await _apiClient.post(
        '/referrals/links',
        data: {
          if (channel != null) 'channel': channel,
          if (campaignId != null) 'campaignId': campaignId,
        },
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('推荐链接生成成功: shortUrl=${data['shortUrl']}');
        return ReferralLinkResponse.fromJson(data);
      }

      throw Exception('生成推荐链接失败');
    } catch (e) {
      debugPrint('生成推荐链接失败: $e');
      rethrow;
    }
  }

  /// 获取默认分享链接
  ///
  /// 这个方法会先尝试生成短链，如果失败则使用用户信息中的默认链接
  Future<String> getDefaultShareLink() async {
    try {
      // 先尝试生成短链
      final linkResponse = await generateReferralLink();
      return linkResponse.shortUrl;
    } catch (e) {
      debugPrint('生成短链失败，尝试获取默认链接: $e');
      // 失败时获取用户信息中的默认链接
      try {
        final meResponse = await getMe();
        return meResponse.referralLink;
      } catch (e2) {
        debugPrint('获取默认链接也失败: $e2');
        rethrow;
      }
    }
  }

  /// 获取指定用户的直推列表（用于伞下树懒加载）
  ///
  /// 调用 GET /referral/user/:accountSequence/direct-referrals (referral-service)
  Future<DirectReferralsResponse> getUserDirectReferrals({
    required String accountSequence,
    int limit = 100,
    int offset = 0,
  }) async {
    try {
      debugPrint('获取用户直推列表: accountSequence=$accountSequence');
      final response = await _apiClient.get(
        '/referral/user/$accountSequence/direct-referrals',
        queryParameters: {
          'limit': limit,
          'offset': offset,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('用户直推列表获取成功: total=${data['total']}');
        return DirectReferralsResponse.fromJson(data);
      }

      throw Exception('获取用户直推列表失败');
    } catch (e) {
      debugPrint('获取用户直推列表失败: $e');
      rethrow;
    }
  }

  // ========== [2026-03-02] 团队预种统计 ==========

  /// 获取团队预种统计（含直推明细）
  ///
  /// 调用 GET /referral/me/team-pre-planting (referral-service)
  Future<TeamPrePlantingResponse> getTeamPrePlanting() async {
    try {
      debugPrint('获取团队预种统计...');
      final response = await _apiClient.get(ApiEndpoints.teamPrePlanting);

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('团队预种统计获取成功: self=${data['selfPrePlantingPortions']}, team=${data['teamPrePlantingPortions']}');
        return TeamPrePlantingResponse.fromJson(data);
      }

      throw Exception('获取团队预种统计失败');
    } catch (e) {
      debugPrint('获取团队预种统计失败: $e');
      rethrow;
    }
  }

  /// 获取团队成员预种明细（分页）
  ///
  /// 调用 GET /referral/me/team-pre-planting/members (referral-service)
  Future<TeamPrePlantingMembersResponse> getTeamPrePlantingMembers({
    int limit = 20,
    int offset = 0,
  }) async {
    try {
      debugPrint('获取团队成员预种明细: limit=$limit, offset=$offset');
      final response = await _apiClient.get(
        ApiEndpoints.teamPrePlantingMembers,
        queryParameters: {
          'limit': limit,
          'offset': offset,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('团队成员预种明细获取成功: total=${data['total']}');
        return TeamPrePlantingMembersResponse.fromJson(data);
      }

      throw Exception('获取团队成员预种明细失败');
    } catch (e) {
      debugPrint('获取团队成员预种明细失败: $e');
      rethrow;
    }
  }
}

// ========== [2026-03-02] 团队预种模型类 ==========

/// 直推成员预种信息
class DirectPrePlantingInfo {
  final String accountSequence;
  final int selfPrePlantingPortions;

  DirectPrePlantingInfo({
    required this.accountSequence,
    required this.selfPrePlantingPortions,
  });

  factory DirectPrePlantingInfo.fromJson(Map<String, dynamic> json) {
    return DirectPrePlantingInfo(
      accountSequence: json['accountSequence']?.toString() ?? '',
      selfPrePlantingPortions: json['selfPrePlantingPortions'] ?? 0,
    );
  }
}

/// 团队预种统计响应
class TeamPrePlantingResponse {
  final int selfPrePlantingPortions;
  final int teamPrePlantingPortions;
  final List<DirectPrePlantingInfo> directReferrals;

  TeamPrePlantingResponse({
    required this.selfPrePlantingPortions,
    required this.teamPrePlantingPortions,
    required this.directReferrals,
  });

  factory TeamPrePlantingResponse.fromJson(Map<String, dynamic> json) {
    return TeamPrePlantingResponse(
      selfPrePlantingPortions: json['selfPrePlantingPortions'] ?? 0,
      teamPrePlantingPortions: json['teamPrePlantingPortions'] ?? 0,
      directReferrals: (json['directReferrals'] as List? ?? [])
          .map((e) => DirectPrePlantingInfo.fromJson(e))
          .toList(),
    );
  }
}

/// 团队成员预种信息
class TeamMemberPrePlanting {
  final String accountSequence;
  final int selfPrePlantingPortions;

  TeamMemberPrePlanting({
    required this.accountSequence,
    required this.selfPrePlantingPortions,
  });

  factory TeamMemberPrePlanting.fromJson(Map<String, dynamic> json) {
    return TeamMemberPrePlanting(
      accountSequence: json['accountSequence']?.toString() ?? '',
      selfPrePlantingPortions: json['selfPrePlantingPortions'] ?? 0,
    );
  }
}

/// 团队成员预种明细响应（分页）
class TeamPrePlantingMembersResponse {
  final List<TeamMemberPrePlanting> members;
  final int total;
  final bool hasMore;

  TeamPrePlantingMembersResponse({
    required this.members,
    required this.total,
    required this.hasMore,
  });

  factory TeamPrePlantingMembersResponse.fromJson(Map<String, dynamic> json) {
    return TeamPrePlantingMembersResponse(
      members: (json['members'] as List? ?? [])
          .map((e) => TeamMemberPrePlanting.fromJson(e))
          .toList(),
      total: json['total'] ?? 0,
      hasMore: json['hasMore'] ?? false,
    );
  }
}
