import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import '../../../core/routes/app_routes.dart';
import '../services/listening_service.dart';
import '../models/listening_exercise_model.dart';

class ListeningExerciseDetailScreen extends StatefulWidget {
  final String exerciseId;

  const ListeningExerciseDetailScreen({
    Key? key,
    required this.exerciseId,
  }) : super(key: key);

  @override
  State<ListeningExerciseDetailScreen> createState() => _ListeningExerciseDetailScreenState();
}

class _ListeningExerciseDetailScreenState extends State<ListeningExerciseDetailScreen> {
  late ListeningExercise exercise;
  late AudioPlayer audioPlayer;
  bool isPlaying = false;
  bool isLoading = true;
  Duration currentPosition = Duration.zero;
  Duration totalDuration = Duration.zero;
  
  Map<String, String> userAnswers = {};
  bool showResults = false;
  bool showTranscript = false;
  int currentQuestionIndex = 0;

  @override
  void initState() {
    super.initState();
    audioPlayer = AudioPlayer();
    _loadExercise();
    _setupAudioPlayer();
  }

  void _loadExercise() {
    final service = ListeningService();
    service.getListeningExercise(widget.exerciseId).then((ex) {
      setState(() {
        exercise = ex;
        isLoading = false;
      });
    }).catchError((e) {
      setState(() {
        isLoading = false;
      });
    });
  }

  void _setupAudioPlayer() {
    audioPlayer.playerStateStream.listen((state) {
      setState(() {
        isPlaying = state.playing;
      });
    });

    audioPlayer.durationStream.listen((duration) {
      if (duration != null) {
        setState(() {
          totalDuration = duration;
        });
      }
    });

    audioPlayer.positionStream.listen((position) {
      setState(() {
        currentPosition = position;
      });
    });
  }

  @override
  void dispose() {
    audioPlayer.dispose();
    super.dispose();
  }

  Future<void> _playPause() async {
    if (isPlaying) {
      await audioPlayer.pause();
    } else {
      try {
        await audioPlayer.setUrl(exercise.audioUrl);
        await audioPlayer.play();
      } catch (e) {
        print('播放音频失败: $e');
      }
    }
  }

  Future<void> _seekTo(Duration position) async {
    await audioPlayer.seek(position);
  }

  void _selectAnswer(String questionId, String answer) {
    setState(() {
      userAnswers[questionId] = answer;
    });
  }

  void _submitAnswers() {
    final service = ListeningService();
    final answers = exercise.questions.map((q) => userAnswers[q.id] ?? '').toList();
    service.submitListeningExercise(
      exerciseId: exercise.id,
      userId: 'current_user_id',
      userAnswers: answers,
      timeSpent: totalDuration.inSeconds,
      playCount: 1,
    ).then((_) {
      setState(() {
        showResults = true;
      });
    }).catchError((_) {
      setState(() {
        showResults = true;
      });
    });
  }

  void _resetExercise() {
    setState(() {
      userAnswers.clear();
      showResults = false;
      currentQuestionIndex = 0;
      showTranscript = false;
    });
    audioPlayer.stop();
  }

  int _getScore() {
    int correct = 0;
    for (var question in exercise.questions) {
      if (userAnswers[question.id] == question.correctAnswer) {
        correct++;
      }
    }
    return (correct / exercise.questions.length * 100).round();
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(exercise.title),
        backgroundColor: Colors.blue[50],
        elevation: 0,
        actions: [
          IconButton(
            icon: Icon(showTranscript ? Icons.visibility_off : Icons.visibility),
            onPressed: () {
              setState(() {
                showTranscript = !showTranscript;
              });
            },
            tooltip: showTranscript ? '隐藏原文' : '显示原文',
          ),
        ],
      ),
      body: Column(
        children: [
          // 音频播放器
          _buildAudioPlayer(),
          
          // 原文显示（可选）
          if (showTranscript) _buildTranscript(),
          
          // 题目区域
          Expanded(
            child: showResults ? _buildResults() : _buildQuestions(),
          ),
          
          // 底部操作按钮
          _buildBottomActions(),
        ],
      ),
    );
  }

  Widget _buildAudioPlayer() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          // 播放控制
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.replay_10),
                onPressed: () {
                  final newPosition = currentPosition - const Duration(seconds: 10);
                  _seekTo(newPosition < Duration.zero ? Duration.zero : newPosition);
                },
              ),
              IconButton(
                icon: Icon(isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled),
                iconSize: 64,
                onPressed: _playPause,
              ),
              IconButton(
                icon: const Icon(Icons.forward_10),
                onPressed: () {
                  final newPosition = currentPosition + const Duration(seconds: 10);
                  _seekTo(newPosition > totalDuration ? totalDuration : newPosition);
                },
              ),
            ],
          ),
          
          // 进度条
          Column(
            children: [
              Slider(
                value: currentPosition.inSeconds.toDouble(),
                max: totalDuration.inSeconds.toDouble(),
                onChanged: (value) {
                  _seekTo(Duration(seconds: value.toInt()));
                },
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(_formatDuration(currentPosition)),
                  Text(_formatDuration(totalDuration)),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTranscript() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.text_snippet, color: Colors.blue[600]),
              const SizedBox(width: 8),
              Text(
                '听力原文',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue[600],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            exercise.transcript,
            style: const TextStyle(
              fontSize: 14,
              height: 1.5,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuestions() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: exercise.questions.length,
      itemBuilder: (context, index) {
        final question = exercise.questions[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 16),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '第${index + 1}题',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  question.question,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 16),
                ...question.options.map((option) {
                  final isSelected = userAnswers[question.id] == option;
                  return Container(
                    margin: const EdgeInsets.only(bottom: 8),
                    child: InkWell(
                      onTap: () => _selectAnswer(question.id, option),
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: isSelected ? Colors.blue : Colors.grey[300]!,
                            width: isSelected ? 2 : 1,
                          ),
                          color: isSelected ? Colors.blue[50] : Colors.white,
                        ),
                        child: Row(
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: isSelected ? Colors.blue : Colors.grey[400]!,
                                  width: 2,
                                ),
                                color: isSelected ? Colors.blue : Colors.white,
                              ),
                              child: isSelected
                                  ? const Icon(
                                      Icons.check,
                                      size: 14,
                                      color: Colors.white,
                                    )
                                  : null,
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Text(
                                option,
                                style: TextStyle(
                                  color: isSelected ? Colors.blue[700] : Colors.black87,
                                  fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                }).toList(),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildResults() {
    final score = _getScore();
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 分数显示
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: score >= 80 ? Colors.green[50] : score >= 60 ? Colors.orange[50] : Colors.red[50],
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: score >= 80 ? Colors.green[200]! : score >= 60 ? Colors.orange[200]! : Colors.red[200]!,
              ),
            ),
            child: Column(
              children: [
                Icon(
                  score >= 80 ? Icons.emoji_events : score >= 60 ? Icons.thumb_up : Icons.refresh,
                  size: 48,
                  color: score >= 80 ? Colors.green[600] : score >= 60 ? Colors.orange[600] : Colors.red[600],
                ),
                const SizedBox(height: 16),
                Text(
                  '得分: $score分',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: score >= 80 ? Colors.green[700] : score >= 60 ? Colors.orange[700] : Colors.red[700],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '正确率: ${userAnswers.length > 0 ? (userAnswers.values.where((answer) => exercise.questions.any((q) => q.correctAnswer == answer)).length / exercise.questions.length * 100).round() : 0}%',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 24),
          
          // 答题详情
          Expanded(
            child: ListView.builder(
              itemCount: exercise.questions.length,
              itemBuilder: (context, index) {
                final question = exercise.questions[index];
                final userAnswer = userAnswers[question.id];
                final isCorrect = userAnswer == question.correctAnswer;
                
                return Card(
                  margin: const EdgeInsets.only(bottom: 12),
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(
                              isCorrect ? Icons.check_circle : Icons.cancel,
                              color: isCorrect ? Colors.green : Colors.red,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              '第${index + 1}题',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Text(question.question),
                        const SizedBox(height: 12),
                        if (userAnswer != null) ...[
                          Text(
                            '你的答案: $userAnswer',
                            style: TextStyle(
                              color: isCorrect ? Colors.green[700] : Colors.red[700],
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          if (!isCorrect) ...[
                            const SizedBox(height: 4),
                            Text(
                              '正确答案: ${question.correctAnswer}',
                              style: TextStyle(
                                color: Colors.green[700],
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ] else ...[
                          Text(
                            '未作答',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontStyle: FontStyle.italic,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '正确答案: ${question.correctAnswer}',
                            style: TextStyle(
                              color: Colors.green[700],
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: showResults
          ? Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: _resetExercise,
                    child: const Text('重新练习'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('返回'),
                  ),
                ),
              ],
            )
          : Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('取消'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: userAnswers.length == exercise.questions.length
                        ? _submitAnswers
                        : null,
                    child: const Text('提交答案'),
                  ),
                ),
              ],
            ),
    );
  }
}