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

/// 待办操作动作代码枚举
enum PendingActionCode {
  adoptionWizard('ADOPTION_WIZARD', '认种向导'),
  settleRewards('SETTLE_REWARDS', '结算奖励'),
  bindPhone('BIND_PHONE', '绑定手机'),
  forceKyc('FORCE_KYC', '强制实名'),
  signContract('SIGN_CONTRACT', '签署合同'),
  updateProfile('UPDATE_PROFILE', '更新资料'),
  specialDeduction('SPECIAL_DEDUCTION', '特殊扣减');

  final String code;
  final String label;
  const PendingActionCode(this.code, this.label);

  static PendingActionCode? fromCode(String code) {
    for (final action in PendingActionCode.values) {
      if (action.code == code) return action;
    }
    return null;
  }
}

/// 待办操作状态枚举
enum PendingActionStatus {
  pending('PENDING'),
  completed('COMPLETED'),
  cancelled('CANCELLED');

  final String value;
  const PendingActionStatus(this.value);

  static PendingActionStatus fromValue(String value) {
    for (final status in PendingActionStatus.values) {
      if (status.value == value) return status;
    }
    return PendingActionStatus.pending;
  }
}

/// 待办操作模型
class PendingAction {
  final int id;
  final int userId;
  final String actionCode;
  final Map<String, dynamic>? actionParams;
  final PendingActionStatus status;
  final int priority;
  final DateTime? expiresAt;
  final DateTime createdAt;
  final DateTime? completedAt;

  PendingAction({
    required this.id,
    required this.userId,
    required this.actionCode,
    this.actionParams,
    required this.status,
    required this.priority,
    this.expiresAt,
    required this.createdAt,
    this.completedAt,
  });

  factory PendingAction.fromJson(Map<String, dynamic> json) {
    return PendingAction(
      id: _parseInt(json['id']),
      userId: _parseInt(json['userId']),
      actionCode: json['actionCode'] as String,
      actionParams: json['actionParams'] as Map<String, dynamic>?,
      status: PendingActionStatus.fromValue(json['status'] as String),
      priority: json['priority'] as int? ?? 0,
      expiresAt: json['expiresAt'] != null
          ? DateTime.parse(json['expiresAt'] as String)
          : null,
      createdAt: DateTime.parse(json['createdAt'] as String),
      completedAt: json['completedAt'] != null
          ? DateTime.parse(json['completedAt'] as String)
          : null,
    );
  }

  static int _parseInt(dynamic value) {
    if (value is int) return value;
    if (value is String) return int.parse(value);
    return 0;
  }

  /// 获取动作代码枚举
  PendingActionCode? get actionCodeEnum => PendingActionCode.fromCode(actionCode);

  /// 获取显示标签
  String get displayLabel => actionCodeEnum?.label ?? actionCode;

  /// 是否已过期
  bool get isExpired {
    if (expiresAt == null) return false;
    return DateTime.now().isAfter(expiresAt!);
  }

  /// 是否待处理
  bool get isPending => status == PendingActionStatus.pending && !isExpired;

  @override
  String toString() =>
      'PendingAction(id: $id, actionCode: $actionCode, status: ${status.value}, priority: $priority)';
}

/// 待办操作列表响应
class PendingActionsResponse {
  final List<PendingAction> actions;
  final int count;

  PendingActionsResponse({
    required this.actions,
    required this.count,
  });

  factory PendingActionsResponse.fromJson(Map<String, dynamic> json) {
    final actionsJson = json['actions'] as List<dynamic>? ?? [];
    return PendingActionsResponse(
      actions: actionsJson
          .map((e) => PendingAction.fromJson(e as Map<String, dynamic>))
          .toList(),
      count: json['count'] as int? ?? actionsJson.length,
    );
  }

  /// 获取按优先级排序的待处理操作（优先级高的在前）
  List<PendingAction> get pendingActionsSorted {
    final pending = actions.where((a) => a.isPending).toList();
    pending.sort((a, b) => b.priority.compareTo(a.priority));
    return pending;
  }

  /// 是否有待处理的操作
  bool get hasPendingActions => pendingActionsSorted.isNotEmpty;

  /// 获取下一个需要执行的操作
  PendingAction? get nextAction =>
      pendingActionsSorted.isNotEmpty ? pendingActionsSorted.first : null;
}

/// 待办操作服务
class PendingActionService {
  final ApiClient _apiClient;

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

  /// 获取当前用户的待办操作列表
  Future<PendingActionsResponse> getMyPendingActions() async {
    debugPrint('[PendingActionService] 获取待办操作列表');

    try {
      final response = await _apiClient.get(ApiEndpoints.pendingActions);
      final data = response.data;
      debugPrint('[PendingActionService] 响应: $data');

      // 解析嵌套的响应结构: {success: true, data: {code: "OK", data: [...]}}
      if (data is Map<String, dynamic>) {
        // 检查是否有嵌套的 data 结构
        final innerData = data['data'];
        if (innerData is Map<String, dynamic>) {
          // 进一步获取内层的 data (实际的操作列表)
          final actionsList = innerData['data'];
          if (actionsList is List) {
            debugPrint('[PendingActionService] 解析到 ${actionsList.length} 个待办操作');
            return PendingActionsResponse(
              actions: actionsList
                  .map((e) => PendingAction.fromJson(e as Map<String, dynamic>))
                  .toList(),
              count: actionsList.length,
            );
          }
        }

        // 旧格式兼容: {actions: [...]}
        if (data.containsKey('actions')) {
          return PendingActionsResponse.fromJson(data);
        }
      }

      // 如果返回的是列表
      if (data is List) {
        return PendingActionsResponse(
          actions: data
              .map((e) => PendingAction.fromJson(e as Map<String, dynamic>))
              .toList(),
          count: data.length,
        );
      }

      debugPrint('[PendingActionService] 无法解析响应数据，返回空列表');
      return PendingActionsResponse(actions: [], count: 0);
    } catch (e) {
      debugPrint('[PendingActionService] 获取待办操作失败: $e');
      rethrow;
    }
  }

  /// 完成待办操作
  Future<void> completeAction(int actionId, {Map<String, dynamic>? resultData}) async {
    debugPrint('[PendingActionService] 完成待办操作: actionId=$actionId');

    try {
      await _apiClient.post(
        '${ApiEndpoints.pendingActions}/$actionId/complete',
        data: resultData != null ? {'resultData': resultData} : null,
      );
      debugPrint('[PendingActionService] 待办操作完成成功');
    } catch (e) {
      debugPrint('[PendingActionService] 完成待办操作失败: $e');
      rethrow;
    }
  }
}
