import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/http/ApiService.dart';

import '../../../tools/tools.dart';

class VideoStudyDetailPage extends StatefulWidget {
  final String studentId;
  final String classId;

  const VideoStudyDetailPage({Key? key, required this.studentId, required this.classId}) : super(key: key);

  @override
  _VideoStudyDetailPageState createState() => _VideoStudyDetailPageState();
}

class Question {
  final String questionDry;
  final String questionType;
  final Map<String, String> options;
  String answer;
  final String answerRight;
  final String descr;
  bool answered;

  Question({
    required this.questionDry,
    required this.questionType,
    required this.options,
    required this.answer,
    required this.answerRight,
    required this.descr,
    this.answered = true, // 默认已作答，立即显示对错
  });

  factory Question.fromJson(Map<String, dynamic> json) {
    String type = json['QUESTIONTYPE'] as String? ?? '1';
    Map<String, String> opts = {};
    if (type == '1' || type == '2' || type == '3') {
      opts['A'] = json['OPTIONA'] as String? ?? '';
      opts['B'] = json['OPTIONB'] as String? ?? '';
      if (type != '3') {
        opts['C'] = json['OPTIONC'] as String? ?? '';
        opts['D'] = json['OPTIOND'] as String? ?? '';
      }
    }
    return Question(
      questionDry: json['QUESTIONDRY'] as String? ?? '',
      questionType: type,
      options: opts,
      answer: json['ANSWER'] as String? ?? '',
      answerRight: json['ANSWERRIGHT'] as String? ?? json['ANSWER'] as String? ?? '',
      descr: json['DESCR'] as String? ?? '',
    );
  }
}

class _VideoStudyDetailPageState extends State<VideoStudyDetailPage> {
  bool loading = true;
  List<Question> questions = [];
  Map<String, dynamic> paperInfo = {};
  int current = 0;
  final Map<String, String> questionTypeMap = {
    '1': '单选题',
    '2': '多选题',
    '3': '判断题',
    '4': '填空题',
  };

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    setState(() => loading = true);
    final res = await ApiService.getExamRecordByStuId(widget.studentId, widget.classId);
    if (res['result'] == 'success') {
      var list = res['varList'] as List;
      questions = list.map((e) => Question.fromJson(e)).toList();
      // 标记所有题目为已作答，直接显示对错
      for (var q in questions) {
        q.answered = true;
      }
      paperInfo = res['paper'] ?? {};
    }
    setState(() => loading = false);
  }

  Widget _buildOptions(Question q) {
    if (q.questionType == '4') {
      return TextField(
        controller: TextEditingController(text: q.answer),
        readOnly: true,
        maxLength: 255,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
        ),
      );
    }
    List<String> keys = q.questionType == '3' ? ['A', 'B'] : ['A', 'B', 'C', 'D'];
    return Column(
      children: keys.map((key) {
        bool isChecked = q.answer.split(',').contains(key);
        bool isCorrect = q.answerRight.split(',').contains(key);
        bool right = q.answered && isCorrect && isChecked;
        bool err   = q.answered && !isCorrect && isChecked;
        bool warn  = q.answered && isCorrect && !isChecked;
        return Container(
          margin: EdgeInsets.symmetric(vertical: 8),
          child: Row(
            children: [
              Container(
                width: 40,
                height: 40,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: right || warn
                      ? Colors.green
                      : err ? Colors.red : Colors.grey.shade200,
                  shape: BoxShape.circle,
                ),
                child: Text(
                  key,
                  style: TextStyle(
                    color: (right || err || warn) ? Colors.white : Colors.black87,
                  ),
                ),
              ),
              SizedBox(width: 16),
              Expanded(
                child: Text(
                  q.options[key] ?? '',
                  style: TextStyle(
                    color: right
                        ? Colors.green
                        : err
                        ? Colors.red
                        : warn
                        ? Colors.green
                        : Colors.black87,
                    fontSize: 16,
                  ),
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  String _renderAnswerText(Question q) {
    if (q.questionType == '3') return q.answer == 'A' ? '对' : '错';
    return q.answer;
  }

  @override
  Widget build(BuildContext context) {
    final q = questions.isNotEmpty ? questions[current] : null;
    return Scaffold(
      appBar: MyAppbar(title: '课程练习详情'),
      body: loading
          ? Center(child: CircularProgressIndicator())
          : questions.isEmpty
          ? NoDataWidget.show()
          : Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部背景 & 进度
            Stack(
              children: [
                Container(
                  width: double.infinity,
                  height: 100,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/study/bgimg1.png'),
                      fit: BoxFit.cover,
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                Positioned.fill(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '考试科目： ${paperInfo['EXAMNAME']}',
                          style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                        Padding(padding: EdgeInsets.symmetric(horizontal: 15), child: Divider(color: Colors.white30, height: 20,),),
                        Text(
                          '当前试题 ${current + 1}/${questions.length}',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      ],
                    )
                  ),
                ),
              ],
            ),
            SizedBox(height: 16),
            // 题干
            if (q != null) ...[
              Text(
                '${current + 1}. ${q.questionDry} （${questionTypeMap[q.questionType]}）',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
              ),
              SizedBox(height: 16),
              _buildOptions(q),
              Divider(),
              Text('我的答案: ${_renderAnswerText(q)}'),
              Text('正确答案: ${q.answerRight}'),
              Text('权威解读: ${q.descr}'),
            ],
            Spacer(),
            // 底部按钮
            Row(
              children: [
                if (current > 0)
                  Expanded(
                    child: CustomButton(
                      text: '上一题',
                      backgroundColor: Colors.grey.shade200,
                      textStyle: TextStyle(color: Colors.black54),
                      onPressed: () => setState(() => current--),
                    ),
                  ),
                if (current > 0 && current < questions.length - 1)
                  SizedBox(width: 16),
                if (current < questions.length - 1)
                  Expanded(
                    child: CustomButton(
                      text: '下一题',
                      backgroundColor: Colors.blue,
                      onPressed: () => setState(() => current++),
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
