import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/learning/modules/level/providers/level_provider.dart';
import 'package:english_learning/features/learning/modules/level/widgets/level_card.dart';
import 'package:english_learning/features/learning/modules/level/widgets/pretest_card.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LevelListScreen extends StatefulWidget {
  final String topicId;
  final String topicTitle;

  const LevelListScreen({
    super.key,
    required this.topicId,
    required this.topicTitle,
  });

  @override
  State<LevelListScreen> createState() => _LevelListScreenState();
}

class _LevelListScreenState extends State<LevelListScreen> {
  @override
  void initState() {
    super.initState();
    _fetchLevels();
  }

  Future<void> _fetchLevels() async {
    final levelProvider = Provider.of<LevelProvider>(context, listen: false);
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    await levelProvider.fetchLevels(widget.topicId, userProvider.jwtToken!);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        iconTheme: const IconThemeData(color: AppColors.whiteColor),
        centerTitle: true,
        title: RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: 'Level list of ',
                style: AppTextStyles.whiteTextStyle.copyWith(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
              TextSpan(
                text: widget.topicTitle,
                style: AppTextStyles.whiteTextStyle.copyWith(
                  fontSize: 14,
                  fontWeight: FontWeight.w900,
                ),
              ),
            ],
          ),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: AppColors.gradientTheme,
          ),
        ),
      ),
      body: Consumer<LevelProvider>(
        builder: (context, levelProvider, child) {
          if (levelProvider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (levelProvider.error != null) {
            return const Center(child: Text('No levels available'));
          } else {
            final pretest = levelProvider.getPretest();
            final otherLevels = levelProvider.levels
                .where((level) => level.isPretest == 0)
                .toList();

            return RefreshIndicator(
              onRefresh: _fetchLevels,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    PretestCard(
                      pretest: pretest,
                      score: levelProvider.getPretestScore(pretest.idLevel),
                      isCompleted:
                          levelProvider.isPretestFinished(pretest.idLevel),
                      isAllowed: levelProvider.isLevelAllowed(pretest.idLevel),
                    ),
                    const SizedBox(height: 12),
                    Expanded(
                      child: GridView.builder(
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          childAspectRatio: 1.0,
                          crossAxisSpacing: 16,
                          mainAxisSpacing: 16,
                        ),
                        itemCount: otherLevels.length,
                        itemBuilder: (context, index) {
                          final level = otherLevels[index];

                          return LevelCard(
                            level: level,
                            isAllowed:
                                levelProvider.isLevelAllowed(level.idLevel),
                            score: levelProvider.getLevelScore(level.idLevel),
                            isCompleted:
                                levelProvider.isLevelCompleted(level.idLevel),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            );
          }
        },
      ),
    );
  }
}
