import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/core/widgets/custom_snackbar.dart';
import 'package:english_learning/core/widgets/global_button.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/complete_submission.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/incomplete_submission.dart';
import 'package:english_learning/features/learning/modules/exercises/providers/exercise_provider.dart';
import 'package:english_learning/features/learning/modules/result/screens/result_screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ExerciseNavigator extends StatelessWidget {
  final VoidCallback? onScrollToTop;
  final bool isReview;
  final String topicId;
  final String topicTitle;

  const ExerciseNavigator({
    super.key,
    required this.onScrollToTop,
    this.isReview = false,
    required this.topicId,
    required this.topicTitle,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer2<ExerciseProvider, UserProvider>(
      builder: (context, exerciseProvider, userProvider, _) {
        final currentExerciseIndex = exerciseProvider.currentExerciseIndex;
        final totalExercises = isReview
            ? exerciseProvider.reviewExercises.length
            : exerciseProvider.exercises.length;
        final isFirstExercise = currentExerciseIndex == 0;
        final isLastExercise = currentExerciseIndex == totalExercises - 1;

        Future<void> submitAnswers() async {
          try {
            final result = await exerciseProvider.submitAnswersAndGetScore();
            print('Submit result: $result');

            if (context.mounted) {
              Navigator.of(context).pushReplacement(
                MaterialPageRoute(
                  builder: (context) => ResultScreen(
                    currentLevel: result['CURRENT_LEVEL_NAME'] ?? '',
                    nextLevel: result['NEXT_LEARNING_NAME'] ?? '',
                    score: int.tryParse(result['SCORE'].toString()) ?? 0,
                    isCompleted: result['IS_PASS'] == 1,
                    stdLearningId: result['STUDENT_LEARNING_ID']?.toString(),
                    topicId: topicId,
                    topicTitle: topicTitle,
                  ),
                ),
              );
            }
          } catch (e) {
            print('Error submitting answers: $e');
            if (context.mounted) {
              CustomSnackBar.show(
                context,
                message: 'Error submitting answers: $e',
                isError: true,
              );
            }
          }
        }

        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (!isFirstExercise)
              Expanded(
                flex: 3,
                child: GlobalButton(
                  text: 'Previous',
                  height: 45,
                  onPressed: () {
                    exerciseProvider.previousQuestion();
                    onScrollToTop?.call();
                  },
                  backgroundColor: Colors.transparent,
                  borderColor: AppColors.blueColor,
                  textColor: AppColors.blueColor,
                  transparentBackground: true,
                ),
              ),
            if (!isFirstExercise && !isLastExercise) const SizedBox(width: 8),
            if (!isLastExercise)
              Expanded(
                flex: 3,
                child: GlobalButton(
                  text: 'Next',
                  height: 45,
                  onPressed: () {
                    exerciseProvider.nextQuestion();
                    onScrollToTop?.call();
                  },
                  backgroundColor: Colors.transparent,
                  borderColor: AppColors.blueColor,
                  textColor: AppColors.blueColor,
                  transparentBackground: true,
                ),
              ),
            if (isLastExercise && !isFirstExercise) const SizedBox(width: 8),
            if (isLastExercise)
              Expanded(
                flex: 5,
                child: GlobalButton(
                  text: isReview ? 'Back to Level List' : 'Submit',
                  height: 45,
                  onPressed: () {
                    if (isReview) {
                      Navigator.of(context).pop();
                    } else {
                      if (exerciseProvider.hasAnsweredQuestions()) {
                        if (exerciseProvider.hasUnansweredQuestions()) {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return IncompleteSubmission(
                                onCheckAgain: () => Navigator.of(context).pop(),
                                onSubmit: () async {
                                  Navigator.of(context).pop();
                                  submitAnswers();
                                },
                              );
                            },
                          );
                        } else {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return CompleteSubmission(
                                onCheckAgain: () => Navigator.of(context).pop(),
                                onSubmit: () async {
                                  Navigator.of(context).pop();
                                  submitAnswers();
                                },
                              );
                            },
                          );
                        }
                      } else {
                        CustomSnackBar.show(
                          context,
                          message:
                              'Please answer at least one question before submitting.',
                          isError: true,
                        );
                      }
                    }
                  },
                  gradient: AppColors.gradientTheme,
                ),
              ),
          ],
        );
      },
    );
  }
}
