import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/learning/modules/exercises/models/exercise_model.dart';
import 'package:english_learning/features/learning/modules/exercises/models/review_exercise_model.dart';
import 'package:english_learning/features/learning/modules/exercises/providers/exercise_provider.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/question/matching_pairs_question.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/question/multiple_choice_question.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/question/true_false_question.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/see_progress_modal.dart';
import 'package:english_learning/features/learning/modules/material/widgets/audio_player_widget.dart';
import 'package:english_learning/features/learning/modules/material/widgets/image_widget.dart';
import 'package:english_learning/features/learning/modules/material/widgets/video_player_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ExerciseContent extends StatefulWidget {
  final dynamic exercise;
  final bool isReview;

  const ExerciseContent({
    super.key,
    required this.exercise,
    this.isReview = false,
  });

  @override
  State<ExerciseContent> createState() => _ExerciseContentState();
}

class _ExerciseContentState extends State<ExerciseContent>
    with WidgetsBindingObserver {
  final GlobalKey<VideoPlayerWidgetState> _videoPlayerKey = GlobalKey();
  final GlobalKey<AudioPlayerWidgetState> _audioPlayerKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    _stopAndResetAllMedia();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      _stopAndResetAllMedia();
    }
  }

  void _stopAndResetAllMedia() {
    _videoPlayerKey.currentState?.stopAndResetVideo();
    _audioPlayerKey.currentState?.stopAndResetAudio();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ExerciseProvider>(builder: (context, provider, child) {
      final exercises =
          widget.isReview ? provider.reviewExercises : provider.exercises;

      if (exercises.isEmpty) {
        return const Center(child: Text('No exercises available'));
      }

      final currentIndex = provider.currentExerciseIndex;
      final currentExercise = exercises[currentIndex];

      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return FadeTransition(
            opacity: animation,
            child: SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0.05, 0),
                end: Offset.zero,
              ).animate(CurvedAnimation(
                parent: animation,
                curve: Curves.easeOutCubic,
              )),
              child: child,
            ),
          );
        },
        child: Container(
          key: ValueKey(currentIndex),
          width: double.infinity,
          decoration: BoxDecoration(
            color: AppColors.whiteColor,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.1),
                spreadRadius: 1,
                blurRadius: 3,
                offset: const Offset(0, 1),
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Question ${currentIndex + 1}',
                      style: AppTextStyles.blackTextStyle.copyWith(
                        fontSize: 18,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    if (!widget.isReview)
                      GestureDetector(
                        onTap: () {
                          showModalBottomSheet(
                            backgroundColor: AppColors.whiteColor,
                            context: context,
                            builder: (context) => const SeeProgressModal(),
                            shape: const RoundedRectangleBorder(
                              borderRadius: BorderRadius.vertical(
                                top: Radius.circular(20),
                              ),
                            ),
                          );
                        },
                        child: Text(
                          'See Progress',
                          style: AppTextStyles.blueTextStyle.copyWith(
                            decoration: TextDecoration.underline,
                            decorationColor: AppColors.blueColor,
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    if (widget.isReview)
                      _buildStatusIndicator(
                          currentExercise as ReviewExerciseDetail),
                  ],
                ),
                const SizedBox(height: 12),
                const Divider(
                  color: AppColors.disableColor,
                  thickness: 1,
                ),
                const SizedBox(height: 12),
                Text(
                  _getQuestionText(currentExercise),
                  style: AppTextStyles.blackTextStyle.copyWith(
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                const SizedBox(height: 16),
                if (widget.exercise.image != null &&
                    widget.exercise.image!.isNotEmpty)
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 16.0),
                      child: ImageWidget(
                        imageFileName: widget.exercise.image!,
                        baseUrl: '${baseUrl}api/uploads/exercise/image/',
                      ),
                    ),
                  ),
                if (widget.exercise.audio != null &&
                    widget.exercise.audio!.isNotEmpty)
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 16.0),
                      child: AudioPlayerWidget(
                        key: _audioPlayerKey,
                        audioFileName: widget.exercise.audio!,
                        baseUrl: '${baseUrl}api/uploads/exercise/audio/',
                      ),
                    ),
                  ),
                if (widget.exercise.video != null &&
                    widget.exercise.video!.isNotEmpty)
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 16.0),
                      child: VideoPlayerWidget(
                        key: _videoPlayerKey,
                        videoUrl: widget.exercise.video!,
                      ),
                    ),
                  ),
                const SizedBox(height: 14),
                _buildQuestionWidget(
                  widget.exercise,
                  widget.isReview,
                )
              ],
            ),
          ),
        ),
      );
    });
  }

  String _getQuestionText(dynamic exercise) {
    if (exercise is ReviewExerciseDetail) {
      return exercise.question;
    } else if (exercise is ExerciseModel) {
      return exercise.question;
    }
    return '';
  }

  Widget _buildQuestionWidget(
    dynamic exercise,
    bool isReview,
  ) {
    String questionType = '';

    if (exercise is ReviewExerciseDetail) {
      questionType = exercise.questionType;
    } else if (exercise is ExerciseModel) {
      questionType = exercise.questionType;
    }

    switch (questionType) {
      case 'MCQ':
        return MultipleChoiceQuestion(
          exercise: exercise,
          isReview: isReview,
        );
      case 'TFQ':
        return TrueFalseQuestion(
          exercise: exercise,
          isReview: isReview,
        );
      case 'MPQ':
        return MatchingPairsQuestion(
          exercise: exercise,
          isReview: isReview,
        );
      default:
        return const Text('Unsupported question type');
    }
  }

  Widget _buildStatusIndicator(ReviewExerciseDetail exercise) {
    if (exercise.questionType == 'MPQ') {
      return Row(
        children: [
          Icon(
            exercise.resultScoreStudent > 0
                ? BootstrapIcons.check_circle_fill
                : BootstrapIcons.x_circle_fill,
            color: exercise.resultScoreStudent > 0 ? Colors.green : Colors.red,
            size: 18,
          ),
          const SizedBox(width: 4),
          Text(
            '${exercise.resultScoreStudent}/${exercise.scoreWeight}',
            style: AppTextStyles.blackTextStyle.copyWith(
              color:
                  exercise.resultScoreStudent > 0 ? Colors.green : Colors.red,
              fontWeight: FontWeight.w500,
              fontSize: 14,
            ),
          ),
        ],
      );
    } else {
      return Row(
        children: [
          Icon(
            exercise.isCorrect == 1
                ? BootstrapIcons.check_circle_fill
                : BootstrapIcons.x_circle_fill,
            color: exercise.isCorrect == 1 ? Colors.green : Colors.red,
            size: 18,
          ),
          const SizedBox(width: 4),
          Text(
            exercise.isCorrect == 1 ? 'Correct' : 'Incorrect',
            style: TextStyle(
              color: exercise.isCorrect == 1 ? Colors.green : Colors.red,
              fontWeight: FontWeight.w500,
              fontSize: 14,
            ),
          ),
        ],
      );
    }
  }
}
