import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:english_learning/features/learning/modules/exercises/providers/exercise_provider.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/content/exercise_content.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/exercise_navigator.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/exercise_progress.dart';
import 'package:english_learning/features/learning/modules/exercises/widgets/instruction_dialog.dart';
import 'package:flutter/material.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:provider/provider.dart';

class ExerciseScreen extends StatefulWidget {
  final String? levelId;
  final String studentLearningId;
  final bool isReview;
  final String topicId; // Tambahkan ini
  final String topicTitle; // Tambahkan ini

  const ExerciseScreen({
    super.key,
    required this.levelId,
    required this.studentLearningId,
    this.isReview = false,
    required this.topicId,
    required this.topicTitle,
  });

  @override
  State<ExerciseScreen> createState() => _ExerciseScreenState();
}

class _ExerciseScreenState extends State<ExerciseScreen> {
  late ScrollController _scrollController;
  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = context.read<ExerciseProvider>();

      if (widget.isReview) {
        provider.fetchReviewExercises(widget.studentLearningId);
      } else {
        provider.fetchExercises(widget.levelId!);
      }
      provider.setStudentLearningId(widget.studentLearningId);
    });
  }

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

  void _scrollToTop() {
    _scrollController.animateTo(
      0,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ExerciseProvider>(builder: (context, provider, child) {
      if (provider.isLoading) {
        return const Scaffold(
          body: Center(child: CircularProgressIndicator()),
        );
      }

      final currentExercise = provider.currentExercise;
      final hasExercises = widget.isReview
          ? provider.reviewExercises.isNotEmpty
          : provider.exercises.isNotEmpty;

      if (!hasExercises || currentExercise == null) {
        return const Scaffold(
          body: Center(child: Text('No exercises available')),
        );
      }

      return Scaffold(
        backgroundColor: AppColors.bgSoftColor,
        appBar: AppBar(
          elevation: 0,
          automaticallyImplyLeading: false,
          leading: widget.isReview
              ? IconButton(
                  icon: const Icon(
                    BootstrapIcons.arrow_left,
                    color: AppColors.whiteColor,
                  ),
                  onPressed: () => Navigator.of(context).pop(),
                )
              : null, // Show back button only in review mode
          iconTheme: const IconThemeData(color: AppColors.whiteColor),
          centerTitle: true,
          title: Text(
            '${provider.nameTopic} - ${provider.nameLevel}',
            style: AppTextStyles.whiteTextStyle.copyWith(
              fontSize: 14,
              fontWeight: FontWeight.w900,
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: AppColors.gradientTheme,
            ),
          ),
          actions: !widget.isReview
              ? [
                  IconButton(
                    icon: const Icon(
                      BootstrapIcons.info_circle,
                      color: AppColors.whiteColor,
                      size: 22,
                    ),
                    onPressed: () => _showInstructions(context),
                  ),
                ]
              : null,
        ),
        body: SafeArea(
          child: Column(
            children: [
              if (!widget.isReview)
                const Padding(
                  padding: EdgeInsets.all(16.0),
                  child: ExerciseProgress(),
                ),
              Expanded(
                child: SingleChildScrollView(
                  controller: _scrollController,
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: Column(
                    children: [
                      const SizedBox(height: 16),
                      ExerciseContent(
                        key: ValueKey(provider.currentExerciseIndex),
                        exercise: currentExercise,
                        isReview: widget.isReview,
                      ),
                      const SizedBox(height: 24),
                      ExerciseNavigator(
                        onScrollToTop: _scrollToTop,
                        isReview: widget.isReview,
                        topicId: widget.topicId,
                        topicTitle: widget.topicTitle,
                      ),
                      const SizedBox(height: 32),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  void _showInstructions(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) => const InstructionsDialog(),
    );
  }
}
