import 'package:english_learning/core/services/dio_client.dart';
import 'package:english_learning/core/services/repositories/student_learning_repository.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/screens/exercise_screen.dart';
import 'package:english_learning/features/learning/modules/level/providers/level_provider.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:english_learning/core/utils/styles/theme.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:provider/provider.dart';

class MaterialScreen extends StatefulWidget {
  final String levelId;
  final bool isReview;
  final String? studentLearningId;
  final String topicId;
  final String topicTitle;

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

  @override
  State<MaterialScreen> createState() => _MaterialScreenState();
}

class _MaterialScreenState extends State<MaterialScreen>
    with WidgetsBindingObserver {
  bool _isLoading = false;
  late StudentLearningRepository _repository;
  final GlobalKey<VideoPlayerWidgetState> _videoPlayerKey = GlobalKey();
  final GlobalKey<AudioPlayerWidgetState> _audioPlayerKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _repository = StudentLearningRepository(DioClient());
    WidgetsBinding.instance.addObserver(this);
  }

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

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

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

  Future<void> _createStudentLearning() async {
    if (widget.isReview && widget.studentLearningId != null) {
      // Jika mode review dan studentLearningId tersedia, langsung navigasi ke ExerciseScreen
      _navigateToExercise(widget.studentLearningId!);
      return;
    }
    setState(() {
      _isLoading = true;
    });

    try {
      final userProvider = Provider.of<UserProvider>(context, listen: false);
      final token = await userProvider.getValidToken();

      if (token == null) {
        throw Exception('No valid token found');
      }

      final result =
          await _repository.createStudentLearning(widget.levelId, token);
      _navigateToExercise(result['payload']['ID_STUDENT_LEARNING']);
    } catch (e) {
      CustomSnackBar.show(context, message: 'Error: $e', isError: true);
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _navigateToExercise(String studentLearningId) {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => ExerciseScreen(
          levelId: widget.levelId,
          studentLearningId: studentLearningId,
          isReview: widget.isReview,
          topicId: widget.topicId,
          topicTitle: widget.topicTitle,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<LevelProvider>(builder: (context, levelProvider, child) {
      final level = levelProvider.levels.firstWhere(
        (level) => level.idLevel == widget.levelId,
        orElse: () => throw Exception('Level not found'),
      );
      return Scaffold(
        appBar: AppBar(
          elevation: 0,
          iconTheme: const IconThemeData(color: AppColors.whiteColor),
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              _stopAndResetAllMedia();
              Navigator.of(context).pop();
            },
          ),
          title: Text(
            '${level.nameTopic} - ${level.nameSection}',
            style: AppTextStyles.whiteTextStyle.copyWith(
              fontSize: 14,
              fontWeight: FontWeight.w900,
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: AppColors.gradientTheme,
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.only(
              left: 16.0,
              right: 16.0,
              bottom: 16,
            ),
            child: Column(
              children: [
                const SizedBox(height: 22),
                HtmlWidget(
                  level.content,
                  customStylesBuilder: (element) {
                    if (element.localName == 'table') {
                      return {'width': '100%', 'border-collapse': 'collapse'};
                    }
                    if (element.localName == 'th' ||
                        element.localName == 'td') {
                      return {
                        'padding': '8px',
                        'border': '1px solid #ddd',
                        'text-align': 'center',
                      };
                    }
                    if (element.localName == 'th') {
                      return {
                        'background-color': '#f5f5f5',
                        'font-weight': 'bold',
                      };
                    }
                    return null;
                  },
                  customWidgetBuilder: (element) {
                    if (element.localName == 'img') {
                      return ImageWidget(
                        imageFileName: element.attributes['src'] ?? '',
                      );
                    }
                    if (element.localName == 'audio') {
                      return AudioPlayerWidget(
                        key: ValueKey('audio_${element.attributes['src']}'),
                        audioFileName: element.attributes['src'] ?? '',
                      );
                    }
                    if (element.localName == 'iframe') {
                      return VideoPlayerWidget(
                        key: ValueKey('video_${element.attributes['src']}'),
                        videoUrl: element.attributes['src'] ?? '',
                      );
                    }
                    return null;
                  },
                  renderMode: RenderMode.column,
                  textStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 32),
                if (!widget.isReview)
                  GlobalButton(
                    text: level.isPretest == 1
                        ? 'Take Pretest'
                        : 'Take Exercises',
                    onPressed: _isLoading
                        ? null
                        : () {
                            _stopAndResetAllMedia();
                            _createStudentLearning();
                          },
                  )
                else
                  GlobalButton(
                    text: 'Start Review',
                    onPressed: _isLoading
                        ? null
                        : () {
                            _stopAndResetAllMedia();
                            _createStudentLearning();
                          },
                  ),
              ],
            ),
          ),
        ),
      );
    });
  }
}
