import '../models/test_models.dart';
import 'test_service.dart';
import '../../../core/models/api_response.dart';
import '../../../core/network/api_client.dart';
import '../../../core/network/api_endpoints.dart';

/// 测试服务实现类（HTTP，使用后端真实API）
class TestServiceImpl implements TestService {
  final ApiClient _apiClient = ApiClient.instance;

  @override
  Future<ApiResponse<List<TestTemplate>>> getTestTemplates() async {
    try {
      final response = await _apiClient.get('${ApiEndpoints.baseUrl}/tests/templates');
      if (response.statusCode == 200) {
        final root = response.data['data'];
        List<dynamic> list = const [];
        if (root is List) {
          list = root;
        } else if (root is Map<String, dynamic>) {
          final v = root['templates'];
          if (v is List) list = v;
        }
        final templates = list.map((e) => TestTemplate.fromJson(e)).toList();
        return ApiResponse.success(message: '获取测试模板成功', data: templates);
      }
      return ApiResponse.error(message: '加载测试模板失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  @override
  Future<ApiResponse<List<TestTemplate>>> getTestTemplatesByType(
    TestType type, {
    bool? isActive,
  }) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.baseUrl}/tests/templates',
        queryParameters: {
          'type': type.name,
          if (isActive != null) 'active': isActive,
        },
      );
      if (response.statusCode == 200) {
        final root = response.data['data'];
        List<dynamic> list = const [];
        if (root is List) {
          list = root;
        } else if (root is Map<String, dynamic>) {
          final v = root['templates'];
          if (v is List) list = v;
        }
        final templates = list.map((e) => TestTemplate.fromJson(e)).toList();
        return ApiResponse.success(message: '获取测试模板成功', data: templates);
      }
      return ApiResponse.error(message: '加载测试模板失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestTemplate>> getTestTemplateById(String id) async {
    try {
      final response = await _apiClient.get('${ApiEndpoints.baseUrl}/tests/templates/$id');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '获取测试模板成功',
          data: TestTemplate.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '模板不存在', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取测试模板失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestSession>> createTestSession({
    required String templateId,
    required String userId,
    Map<String, dynamic>? metadata,
  }) async {
    try {
      final response = await _apiClient.post(
        '${ApiEndpoints.baseUrl}/tests/sessions',
        data: {
          'template_id': templateId,
          'user_id': userId,
          'metadata': metadata ?? {},
        },
      );
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '创建测试会话成功',
          data: TestSession.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '创建测试会话失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '创建测试会话失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestSession>> startTest(String sessionId) async {
    try {
      final response = await _apiClient.put('${ApiEndpoints.baseUrl}/tests/sessions/$sessionId/start');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '测试已开始',
          data: TestSession.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '开始测试失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '开始测试失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestSession>> submitAnswer({
    required String sessionId,
    required UserAnswer answer,
  }) async {
    try {
      final response = await _apiClient.post(
        '${ApiEndpoints.baseUrl}/tests/sessions/$sessionId/answers',
        data: answer.toJson(),
      );
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '答案提交成功',
          data: TestSession.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '提交答案失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '提交答案失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestSession>> pauseTest(String sessionId) async {
    try {
      final response = await _apiClient.put('${ApiEndpoints.baseUrl}/tests/sessions/$sessionId/pause');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '测试已暂停',
          data: TestSession.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '暂停测试失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '暂停测试失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestSession>> resumeTest(String sessionId) async {
    try {
      final response = await _apiClient.put('${ApiEndpoints.baseUrl}/tests/sessions/$sessionId/resume');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '测试已恢复',
          data: TestSession.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '恢复测试失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '恢复测试失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestResult>> completeTest({
    required String sessionId,
    required List<UserAnswer> answers,
  }) async {
    try {
      final response = await _apiClient.put(
        '${ApiEndpoints.baseUrl}/tests/sessions/$sessionId/complete',
        data: {
          'answers': answers.map((a) => a.toJson()).toList(),
        },
      );
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '提交测试成功',
          data: TestResult.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '完成测试失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '完成测试失败: $e');
    }
  }

  @override
  Future<ApiResponse<List<TestResult>>> getUserTestHistory(
    String userId, {
    int page = 1,
    int limit = 10,
  }) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.baseUrl}/tests/sessions',
        queryParameters: {
          'page': page,
          'limit': limit,
        },
      );
      if (response.statusCode == 200) {
        final root = response.data['data'];
        List<dynamic> list = const [];
        if (root is List) {
          list = root;
        } else if (root is Map<String, dynamic>) {
          final v = root['sessions'];
          if (v is List) list = v;
        }
        final results = list.map((e) => TestResult.fromJson(e)).toList();
        return ApiResponse.success(message: '获取测试历史成功', data: results);
      }
      return ApiResponse.error(message: '获取测试历史失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取测试历史失败: $e');
    }
  }

  @override
  Future<ApiResponse<List<TestResult>>> getRecentTestResults(
    String userId, {
    int limit = 10,
  }) async {
    try {
      final response = await _apiClient.get(
        '${ApiEndpoints.baseUrl}/tests/sessions',
        queryParameters: {
          'limit': limit,
        },
      );
      if (response.statusCode == 200) {
        final root = response.data['data'];
        List<dynamic> list = const [];
        if (root is List) {
          list = root;
        } else if (root is Map<String, dynamic>) {
          final v = root['sessions'];
          if (v is List) list = v;
        }
        final results = list.map((e) => TestResult.fromJson(e)).toList();
        return ApiResponse.success(message: '获取最近测试结果成功', data: results);
      }
      return ApiResponse.error(message: '获取最近测试结果失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取最近测试结果失败: $e');
    }
  }

  @override
  Future<ApiResponse<TestResult>> getTestResultById(String resultId) async {
    try {
      final response = await _apiClient.get('${ApiEndpoints.baseUrl}/tests/results/$resultId');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '获取测试结果成功',
          data: TestResult.fromJson(response.data['data']),
        );
      }
      return ApiResponse.error(message: '测试结果不存在', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取测试结果失败: $e');
    }
  }

  @override
  Future<ApiResponse<Map<SkillType, double>>> getUserSkillStatistics(
    String userId, {
    int? daysPeriod,
  }) async {
    try {
      final response = await _apiClient.get('${ApiEndpoints.baseUrl}/tests/stats');
      if (response.statusCode == 200) {
        final Map<String, dynamic> data = response.data['data'] ?? {};
        final Map<SkillType, double> stats = {};
        data.forEach((k, v) {
          final skill = SkillType.values.firstWhere((s) => s.name == k, orElse: () => SkillType.reading);
          stats[skill] = (v as num).toDouble();
        });
        return ApiResponse.success(message: '获取技能统计成功', data: stats);
      }
      return ApiResponse.error(message: '获取技能统计失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取技能统计失败: $e');
    }
  }

  @override
  Future<ApiResponse<Map<String, dynamic>>> getQuestionStatistics() async {
    try {
      final response = await _apiClient.get('${ApiEndpoints.baseUrl}/tests/stats');
      if (response.statusCode == 200) {
        return ApiResponse.success(
          message: '获取题目统计成功',
          data: response.data['data'] ?? {},
        );
      }
      return ApiResponse.error(message: '获取题目统计失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '获取题目统计失败: $e');
    }
  }

  @override
  Future<ApiResponse<bool>> deleteTestResult(String resultId) async {
    try {
      final response = await _apiClient.delete('${ApiEndpoints.baseUrl}/tests/results/$resultId');
      if (response.statusCode == 200) {
        return ApiResponse.success(message: '删除测试结果成功', data: true);
      }
      return ApiResponse.error(message: '删除测试结果失败', code: response.statusCode);
    } catch (e) {
      return ApiResponse.error(message: '删除测试结果失败: $e');
    }
  }
}