import 'package:dio/dio.dart';
import '../../../../core/network/api_endpoints.dart';

class QuizOptionModel {
  final String label;
  final String text;

  const QuizOptionModel({required this.label, required this.text});

  factory QuizOptionModel.fromJson(Map<String, dynamic> json) {
    return QuizOptionModel(
      label: json['label'] as String,
      text: json['text'] as String,
    );
  }
}

class QuizQuestionModel {
  final String scenarioId;
  final String title;
  final String? shortDescription;
  final String? scenarioParagraph;
  final Map<String, dynamic>? givensTable;
  final String? riskLevel;
  final String? difficulty;
  final String? eventType;
  final List<QuizOptionModel> options;
  final String correctLabel;
  final String? bestAnswerRationale;
  final Map<String, String> otherExplanations;

  const QuizQuestionModel({
    required this.scenarioId,
    required this.title,
    this.shortDescription,
    this.scenarioParagraph,
    this.givensTable,
    this.riskLevel,
    this.difficulty,
    this.eventType,
    required this.options,
    required this.correctLabel,
    this.bestAnswerRationale,
    this.otherExplanations = const {},
  });

  factory QuizQuestionModel.fromJson(Map<String, dynamic> json) {
    final opts = (json['options'] as List<dynamic>?)
            ?.map((e) => QuizOptionModel.fromJson(e as Map<String, dynamic>))
            .toList() ??
        [];

    final rawExplanations = json['other_explanations'];
    final explanations = <String, String>{};
    if (rawExplanations is Map) {
      rawExplanations.forEach((k, v) {
        explanations[k.toString()] = v.toString();
      });
    }

    return QuizQuestionModel(
      scenarioId: json['scenario_id'] as String,
      title: json['title'] as String,
      shortDescription: json['short_description'] as String?,
      scenarioParagraph: json['scenario_paragraph'] as String?,
      givensTable: json['givens_table'] as Map<String, dynamic>?,
      riskLevel: json['risk_level'] as String?,
      difficulty: json['difficulty'] as String?,
      eventType: json['event_type'] as String?,
      options: opts,
      correctLabel: json['correct_label'] as String,
      bestAnswerRationale: json['best_answer_rationale'] as String?,
      otherExplanations: explanations,
    );
  }

  /// Get the correct option's text
  String get correctAnswerText {
    final opt = options.where((o) => o.label == correctLabel).firstOrNull;
    return opt?.text ?? '';
  }

  /// Get explanation for a selected answer text
  String getExplanation(String selectedText) {
    if (selectedText == correctAnswerText) {
      return bestAnswerRationale ?? 'Correct!';
    }
    return otherExplanations[selectedText] ?? 'Incorrect choice.';
  }
}

class QuizStartResponseModel {
  final int quizId;
  final int attemptId;
  final int totalQuestions;
  final List<QuizQuestionModel> questions;

  const QuizStartResponseModel({
    required this.quizId,
    required this.attemptId,
    required this.totalQuestions,
    required this.questions,
  });

  factory QuizStartResponseModel.fromJson(Map<String, dynamic> json) {
    return QuizStartResponseModel(
      quizId: (json['quiz_id'] as num).toInt(),
      attemptId: (json['attempt_id'] as num).toInt(),
      totalQuestions: (json['total_questions'] as num).toInt(),
      questions: (json['questions'] as List<dynamic>)
          .map((e) => QuizQuestionModel.fromJson(e as Map<String, dynamic>))
          .toList(),
    );
  }
}

class QuizAnswerResultModel {
  final String scenarioId;
  final String selectedAnswer;
  final String correctAnswer;
  final bool isCorrect;
  final String? explanation;
  final String? correctRationale;

  const QuizAnswerResultModel({
    required this.scenarioId,
    required this.selectedAnswer,
    required this.correctAnswer,
    required this.isCorrect,
    this.explanation,
    this.correctRationale,
  });

  factory QuizAnswerResultModel.fromJson(Map<String, dynamic> json) {
    return QuizAnswerResultModel(
      scenarioId: json['scenario_id'] as String,
      selectedAnswer: json['selected_answer'] as String,
      correctAnswer: json['correct_answer'] as String,
      isCorrect: json['is_correct'] as bool,
      explanation: json['explanation'] as String?,
      correctRationale: json['correct_rationale'] as String?,
    );
  }
}

class QuizSubmitResultModel {
  final int score;
  final int correct;
  final int total;
  final int percentage;
  final List<QuizAnswerResultModel> results;

  const QuizSubmitResultModel({
    required this.score,
    required this.correct,
    required this.total,
    required this.percentage,
    required this.results,
  });

  factory QuizSubmitResultModel.fromJson(Map<String, dynamic> json) {
    return QuizSubmitResultModel(
      score: (json['score'] as num).toInt(),
      correct: (json['correct'] as num).toInt(),
      total: (json['total'] as num).toInt(),
      percentage: (json['percentage'] as num).toInt(),
      results: (json['results'] as List<dynamic>)
          .map((e) =>
              QuizAnswerResultModel.fromJson(e as Map<String, dynamic>))
          .toList(),
    );
  }
}

class FilterOptionsModel {
  final List<String> categories;
  final List<String> difficulties;
  final List<String> riskLevels;

  const FilterOptionsModel({
    this.categories = const [],
    this.difficulties = const [],
    this.riskLevels = const [],
  });

  factory FilterOptionsModel.fromJson(Map<String, dynamic> json) {
    return FilterOptionsModel(
      categories: List<String>.from(json['categories'] ?? []),
      difficulties: List<String>.from(json['difficulties'] ?? []),
      riskLevels: List<String>.from(json['risk_levels'] ?? []),
    );
  }
}

class QuizRemoteDatasource {
  final Dio _dio;

  QuizRemoteDatasource(this._dio);

  Future<FilterOptionsModel> getFilters() async {
    final response = await _dio.get(ApiEndpoints.filters);
    return FilterOptionsModel.fromJson(response.data as Map<String, dynamic>);
  }

  Future<QuizStartResponseModel> startQuiz({
    required int numQuestions,
    String? difficulty,
    String? category,
  }) async {
    final response = await _dio.post(
      ApiEndpoints.quizStart,
      data: {
        'num_questions': numQuestions,
        if (difficulty != null) 'difficulty': difficulty,
        if (category != null) 'category': category,
      },
    );
    return QuizStartResponseModel.fromJson(
        response.data as Map<String, dynamic>);
  }

  Future<QuizSubmitResultModel> submitQuiz({
    required int attemptId,
    required List<Map<String, String>> answers,
  }) async {
    final response = await _dio.post(
      ApiEndpoints.quizSubmit(attemptId),
      data: answers,
    );
    return QuizSubmitResultModel.fromJson(
        response.data as Map<String, dynamic>);
  }
}