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

// ============================================
// [2026-02-19] 树转让 API 服务（纯新增）
// ============================================
//
// 树转让功能的 Flutter 端 API 调用服务。
// 用户可将已认种的果树转让给其他用户。
//
// === API 端点 ===
// 所有端点走 transfer-service：
// - POST /transfers                  发起转让
// - POST /transfers/:no/confirm      卖方确认
// - POST /transfers/:no/cancel       取消转让
// - GET  /transfers                   我的转让记录
// - GET  /transfers/:no              转让详情
//
// === 与现有 PlantingService 的关系 ===
// 完全独立。PlantingService 处理认种购买，
// TransferService 处理已认种树的所有权转让。
//
// === 回滚方式 ===
// 删除此文件 + DI 注册 + 路由 + 页面文件 + profile 入口

/// 转让订单状态（13 种 Saga 步骤）
enum TransferOrderStatus {
  pending,                // 待卖方确认
  sellerConfirmed,        // 卖方已确认
  paymentFrozen,          // 买方资金已冻结
  treesLocked,            // 卖方树已锁定
  ownershipTransferred,   // 所有权已变更
  contributionAdjusted,   // 算力已调整
  statsUpdated,           // 团队统计已更新
  paymentSettled,         // 资金已结算
  completed,              // 转让完成
  cancelled,              // 已取消
  failed,                 // 失败
  rollingBack,            // 补偿中
  rolledBack,             // 已回滚
}

/// 转让订单
class TransferOrder {
  final String transferOrderNo;
  final String sellerAccountSequence;
  final String buyerAccountSequence;
  final int treeCount;
  final double pricePerTree;
  final double totalPrice;
  final double platformFeeRate;
  final double platformFeeAmount;
  final double sellerReceiveAmount;
  final TransferOrderStatus status;
  final DateTime createdAt;
  final DateTime? completedAt;
  final DateTime? cancelledAt;
  final String? cancelReason;

  TransferOrder({
    required this.transferOrderNo,
    required this.sellerAccountSequence,
    required this.buyerAccountSequence,
    required this.treeCount,
    required this.pricePerTree,
    required this.totalPrice,
    required this.platformFeeRate,
    required this.platformFeeAmount,
    required this.sellerReceiveAmount,
    required this.status,
    required this.createdAt,
    this.completedAt,
    this.cancelledAt,
    this.cancelReason,
  });

  /// 是否为终态
  bool get isTerminal =>
      status == TransferOrderStatus.completed ||
      status == TransferOrderStatus.cancelled ||
      status == TransferOrderStatus.rolledBack;

  /// 是否可取消（PENDING 或 SELLER_CONFIRMED 阶段）
  bool get isCancellable =>
      status == TransferOrderStatus.pending ||
      status == TransferOrderStatus.sellerConfirmed;

  /// 是否待卖方确认
  bool get isPendingSellerConfirm =>
      status == TransferOrderStatus.pending;

  factory TransferOrder.fromJson(Map<String, dynamic> json) {
    return TransferOrder(
      transferOrderNo: json['transferOrderNo'] ?? '',
      sellerAccountSequence: json['sellerAccountSequence'] ?? '',
      buyerAccountSequence: json['buyerAccountSequence'] ?? '',
      treeCount: json['treeCount'] ?? 0,
      pricePerTree: _toDouble(json['pricePerTree']),
      totalPrice: _toDouble(json['totalPrice']),
      platformFeeRate: _toDouble(json['platformFeeRate']),
      platformFeeAmount: _toDouble(json['platformFeeAmount']),
      sellerReceiveAmount: _toDouble(json['sellerReceiveAmount']),
      status: _parseStatus(json['status']),
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
      completedAt: json['completedAt'] != null
          ? DateTime.parse(json['completedAt'])
          : null,
      cancelledAt: json['cancelledAt'] != null
          ? DateTime.parse(json['cancelledAt'])
          : null,
      cancelReason: json['cancelReason'],
    );
  }

  static double _toDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) return double.tryParse(value) ?? 0.0;
    return 0.0;
  }

  static TransferOrderStatus _parseStatus(String? status) {
    switch (status) {
      case 'PENDING': return TransferOrderStatus.pending;
      case 'SELLER_CONFIRMED': return TransferOrderStatus.sellerConfirmed;
      case 'PAYMENT_FROZEN': return TransferOrderStatus.paymentFrozen;
      case 'TREES_LOCKED': return TransferOrderStatus.treesLocked;
      case 'OWNERSHIP_TRANSFERRED': return TransferOrderStatus.ownershipTransferred;
      case 'CONTRIBUTION_ADJUSTED': return TransferOrderStatus.contributionAdjusted;
      case 'STATS_UPDATED': return TransferOrderStatus.statsUpdated;
      case 'PAYMENT_SETTLED': return TransferOrderStatus.paymentSettled;
      case 'COMPLETED': return TransferOrderStatus.completed;
      case 'CANCELLED': return TransferOrderStatus.cancelled;
      case 'FAILED': return TransferOrderStatus.failed;
      case 'ROLLING_BACK': return TransferOrderStatus.rollingBack;
      case 'ROLLED_BACK': return TransferOrderStatus.rolledBack;
      default: return TransferOrderStatus.pending;
    }
  }
}

/// 转让状态变更日志
class TransferStatusLog {
  final String fromStatus;
  final String toStatus;
  final String? reason;
  final DateTime createdAt;

  TransferStatusLog({
    required this.fromStatus,
    required this.toStatus,
    this.reason,
    required this.createdAt,
  });

  factory TransferStatusLog.fromJson(Map<String, dynamic> json) {
    return TransferStatusLog(
      fromStatus: json['fromStatus'] ?? '',
      toStatus: json['toStatus'] ?? '',
      reason: json['reason'],
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
    );
  }
}

/// 转让订单详情（含状态日志）
class TransferOrderDetail extends TransferOrder {
  final List<TransferStatusLog> statusLogs;
  final List<String> plantingOrderNos;

  TransferOrderDetail({
    required super.transferOrderNo,
    required super.sellerAccountSequence,
    required super.buyerAccountSequence,
    required super.treeCount,
    required super.pricePerTree,
    required super.totalPrice,
    required super.platformFeeRate,
    required super.platformFeeAmount,
    required super.sellerReceiveAmount,
    required super.status,
    required super.createdAt,
    super.completedAt,
    super.cancelledAt,
    super.cancelReason,
    required this.statusLogs,
    required this.plantingOrderNos,
  });

  factory TransferOrderDetail.fromJson(Map<String, dynamic> json) {
    final base = TransferOrder.fromJson(json);
    return TransferOrderDetail(
      transferOrderNo: base.transferOrderNo,
      sellerAccountSequence: base.sellerAccountSequence,
      buyerAccountSequence: base.buyerAccountSequence,
      treeCount: base.treeCount,
      pricePerTree: base.pricePerTree,
      totalPrice: base.totalPrice,
      platformFeeRate: base.platformFeeRate,
      platformFeeAmount: base.platformFeeAmount,
      sellerReceiveAmount: base.sellerReceiveAmount,
      status: base.status,
      createdAt: base.createdAt,
      completedAt: base.completedAt,
      cancelledAt: base.cancelledAt,
      cancelReason: base.cancelReason,
      statusLogs: (json['statusLogs'] as List<dynamic>?)
              ?.map((e) => TransferStatusLog.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      plantingOrderNos: (json['plantingOrderNos'] as List<dynamic>?)
              ?.map((e) => e.toString())
              .toList() ??
          [],
    );
  }
}

// ============================================
// 树转让 API 服务
// ============================================

/// 树转让 API 服务
///
/// [2026-02-19] 纯新增：提供树转让功能的所有 API 调用
class TransferService {
  final ApiClient _apiClient;

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

  /// 发起转让
  ///
  /// [buyerAccountSequence] 买方账号
  /// [plantingOrderNos] 要转让的认种订单号列表（空列表时由后端自动选择）
  /// [treeCount] 转让棵数
  Future<TransferOrder> createTransfer({
    required String buyerAccountSequence,
    required List<String> plantingOrderNos,
    required int treeCount,
  }) async {
    try {
      debugPrint('[TransferService] 发起转让: buyer=$buyerAccountSequence, treeCount=$treeCount');
      final response = await _apiClient.post(
        '/transfers',
        data: {
          'buyerAccountSequence': buyerAccountSequence,
          'plantingOrderNos': plantingOrderNos,
          'treeCount': treeCount,
        },
      );

      if (response.statusCode == 201 || response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[TransferService] 转让创建成功: ${data['transferOrderNo']}');
        return TransferOrder.fromJson(data);
      }

      throw Exception('发起转让失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[TransferService] 发起转让失败: $e');
      rethrow;
    }
  }

  /// 卖方确认转让
  Future<TransferOrder> sellerConfirm(String transferOrderNo) async {
    try {
      debugPrint('[TransferService] 卖方确认: $transferOrderNo');
      final response = await _apiClient.post('/transfers/$transferOrderNo/confirm');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        return TransferOrder.fromJson(data);
      }

      throw Exception('确认转让失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[TransferService] 确认转让失败: $e');
      rethrow;
    }
  }

  /// 取消转让
  Future<void> cancelTransfer(String transferOrderNo, {String? reason}) async {
    try {
      debugPrint('[TransferService] 取消转让: $transferOrderNo');
      await _apiClient.post(
        '/transfers/$transferOrderNo/cancel',
        data: {'reason': reason ?? '用户主动取消'},
      );
      debugPrint('[TransferService] 取消成功');
    } catch (e) {
      debugPrint('[TransferService] 取消转让失败: $e');
      rethrow;
    }
  }

  /// 获取我的转让记录（买方+卖方）
  Future<List<TransferOrder>> getMyTransfers({
    int page = 1,
    int pageSize = 20,
    String? role, // 'seller' | 'buyer' | null(全部)
  }) async {
    try {
      debugPrint('[TransferService] 获取转让记录: role=$role');
      final response = await _apiClient.get(
        '/transfers',
        queryParameters: {
          'limit': pageSize,
          'offset': (page - 1) * pageSize,
          if (role != null) 'role': role,
        },
      );

      if (response.statusCode == 200) {
        List<dynamic> items;
        if (response.data is List) {
          items = response.data as List<dynamic>;
        } else if (response.data is Map<String, dynamic>) {
          items = (response.data as Map<String, dynamic>)['items'] as List<dynamic>? ?? [];
        } else {
          items = [];
        }
        return items
            .map((e) => TransferOrder.fromJson(e as Map<String, dynamic>))
            .toList();
      }

      throw Exception('获取转让记录失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[TransferService] 获取转让记录失败: $e');
      rethrow;
    }
  }

  /// 获取转让详情（含状态日志）
  Future<TransferOrderDetail> getTransferDetail(String transferOrderNo) async {
    try {
      debugPrint('[TransferService] 获取转让详情: $transferOrderNo');
      final response = await _apiClient.get('/transfers/$transferOrderNo');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        return TransferOrderDetail.fromJson(data);
      }

      throw Exception('获取转让详情失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[TransferService] 获取转让详情失败: $e');
      rethrow;
    }
  }
}
