import '../../../core/models/api_response.dart';
import '../../../core/services/enhanced_api_service.dart';
import '../models/test_models.dart';

/// 综合测试API服务类
/// 使用后端API替代静态数据
class TestApiService {
  static final TestApiService _instance = TestApiService._internal();
  factory TestApiService() => _instance;
  TestApiService._internal();

  final EnhancedApiService _enhancedApiService = EnhancedApiService();
  
  // 缓存时长配置
  static const Duration _shortCacheDuration = Duration(minutes: 5);
  static const Duration _longCacheDuration = Duration(hours: 1);

  /// 获取所有测试模板
  Future<ApiResponse<List<TestTemplate>>> getTestTemplates() async {
    try {
      final response = await _enhancedApiService.get<List<TestTemplate>>(
        '/tests/templates',
        cacheDuration: _longCacheDuration,
        fromJson: (data) {
          final templates = data['templates'] as List?;
          if (templates == null) return [];
          return templates.map((json) => TestTemplate.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试模板成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  /// 根据类型获取测试模板
  Future<ApiResponse<List<TestTemplate>>> getTestTemplatesByType(
    TestType type,
  ) async {
    try {
      final response = await _enhancedApiService.get<List<TestTemplate>>(
        '/tests/templates',
        queryParameters: {
          'type': type.toString().split('.').last,
        },
        cacheDuration: _longCacheDuration,
        fromJson: (data) {
          final templates = data['templates'] as List?;
          if (templates == null) return [];
          return templates.map((json) => TestTemplate.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试模板成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  /// 根据ID获取测试模板
  Future<ApiResponse<TestTemplate>> getTestTemplateById(String id) async {
    try {
      final response = await _enhancedApiService.get<TestTemplate>(
        '/tests/templates/$id',
        cacheDuration: _longCacheDuration,
        fromJson: (data) => TestTemplate.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试模板成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  /// 创建测试会话
  Future<ApiResponse<TestSession>> createTestSession({
    required String templateId,
    required String userId,
  }) async {
    try {
      final response = await _enhancedApiService.post<TestSession>(
        '/tests/sessions',
        data: {
          'template_id': templateId,
          'user_id': userId,
        },
        fromJson: (data) => TestSession.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '创建测试会话成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '创建测试会话失败: $e');
    }
  }

  /// 开始测试
  Future<ApiResponse<TestSession>> startTest(String sessionId) async {
    try {
      final response = await _enhancedApiService.put<TestSession>(
        '/tests/sessions/$sessionId/start',
        fromJson: (data) => TestSession.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '开始测试成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '开始测试失败: $e');
    }
  }

  /// 提交答案
  Future<ApiResponse<TestSession>> submitAnswer({
    required String sessionId,
    required UserAnswer answer,
  }) async {
    try {
      final response = await _enhancedApiService.post<TestSession>(
        '/tests/sessions/$sessionId/answers',
        data: {
          'question_id': answer.questionId,
          'answer': answer.answer,
        },
        fromJson: (data) => TestSession.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '提交答案成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '提交答案失败: $e');
    }
  }

  /// 暂停测试
  Future<ApiResponse<TestSession>> pauseTest(String sessionId) async {
    try {
      final response = await _enhancedApiService.put<TestSession>(
        '/tests/sessions/$sessionId/pause',
        fromJson: (data) => TestSession.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '测试已暂停');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '暂停测试失败: $e');
    }
  }

  /// 恢复测试
  Future<ApiResponse<TestSession>> resumeTest(String sessionId) async {
    try {
      final response = await _enhancedApiService.put<TestSession>(
        '/tests/sessions/$sessionId/resume',
        fromJson: (data) => TestSession.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '测试已恢复');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '恢复测试失败: $e');
    }
  }

  /// 完成测试
  Future<ApiResponse<TestResult>> completeTest(String sessionId) async {
    try {
      final response = await _enhancedApiService.put<TestResult>(
        '/tests/sessions/$sessionId/complete',
        fromJson: (data) => TestResult.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '完成测试成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '完成测试失败: $e');
    }
  }

  /// 获取测试结果
  Future<ApiResponse<TestResult>> getTestResult(String sessionId) async {
    try {
      final response = await _enhancedApiService.get<TestResult>(
        '/tests/sessions/$sessionId/result',
        cacheDuration: _shortCacheDuration,
        fromJson: (data) => TestResult.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试结果成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试结果失败: $e');
    }
  }

  /// 获取用户测试历史
  Future<ApiResponse<List<TestSession>>> getUserTestHistory({
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<TestSession>>(
        '/tests/sessions',
        queryParameters: {
          'page': page,
          'limit': limit,
        },
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final sessions = data['sessions'] as List?;
          if (sessions == null) return [];
          return sessions.map((json) => TestSession.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试历史成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试历史失败: $e');
    }
  }

  /// 获取用户测试统计
  Future<ApiResponse<Map<String, dynamic>>> getUserTestStats() async {
    try {
      final response = await _enhancedApiService.get<Map<String, dynamic>>(
        '/tests/stats',
        cacheDuration: _shortCacheDuration,
        fromJson: (data) => data,
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试统计成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试统计失败: $e');
    }
  }

  /// 获取最近的测试结果
  Future<ApiResponse<List<TestResult>>> getRecentTestResults(
    String? userId, {
    int limit = 5,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<TestResult>>(
        '/tests/sessions/recent',
        queryParameters: {
          if (userId != null) 'user_id': userId,
          'limit': limit,
        },
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final sessions = data['sessions'] as List?;
          if (sessions == null) return [];
          return sessions.map((json) => TestResult.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取最近测试结果成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取最近测试结果失败: $e');
    }
  }

  /// 获取测试结果详情
  Future<ApiResponse<TestResult>> getTestResultById(String resultId) async {
    try {
      final response = await _enhancedApiService.get<TestResult>(
        '/tests/results/$resultId',
        cacheDuration: _shortCacheDuration,
        fromJson: (data) => TestResult.fromJson(data['data'] ?? data),
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取测试结果成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取测试结果失败: $e');
    }
  }

  /// 获取用户技能统计
  Future<ApiResponse<Map<SkillType, double>>> getUserSkillStatistics(
    String userId,
  ) async {
    try {
      final response = await _enhancedApiService.get<Map<SkillType, double>>(
        '/tests/users/$userId/skills',
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final skillsData = data['skills'] as Map<String, dynamic>?;
          if (skillsData == null) return {};
          
          final result = <SkillType, double>{};
          skillsData.forEach((key, value) {
            final skillType = _parseSkillType(key);
            if (skillType != null) {
              result[skillType] = (value as num).toDouble();
            }
          });
          return result;
        },
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取技能统计成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取技能统计失败: $e');
    }
  }

  /// 获取题目统计
  Future<ApiResponse<Map<String, dynamic>>> getQuestionStatistics() async {
    try {
      final response = await _enhancedApiService.get<Map<String, dynamic>>(
        '/tests/questions/statistics',
        cacheDuration: _longCacheDuration,
        fromJson: (data) => data,
      );
      
      if (response.success && response.data != null) {
        return ApiResponse.success(data: response.data!, message: '获取题目统计成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '获取题目统计失败: $e');
    }
  }

  /// 删除测试结果
  Future<ApiResponse<void>> deleteTestResult(String resultId) async {
    try {
      final response = await _enhancedApiService.delete<void>(
        '/tests/results/$resultId',
        fromJson: (data) => null,
      );
      
      if (response.success) {
        return ApiResponse.success(message: '删除测试结果成功');
      } else {
        return ApiResponse.error(message: response.message);
      }
    } catch (e) {
      return ApiResponse.error(message: '删除测试结果失败: $e');
    }
  }

  /// 解析技能类型
  SkillType? _parseSkillType(String key) {
    switch (key.toLowerCase()) {
      case 'vocabulary':
        return SkillType.vocabulary;
      case 'grammar':
        return SkillType.grammar;
      case 'reading':
        return SkillType.reading;
      case 'listening':
        return SkillType.listening;
      case 'speaking':
        return SkillType.speaking;
      case 'writing':
        return SkillType.writing;
      default:
        return null;
    }
  }
}
