import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/learning/modules/level/screens/level_list_screen.dart';
import 'package:english_learning/features/learning/modules/topics/providers/topic_provider.dart';
import 'package:english_learning/features/learning/modules/topics/widgets/topic_card.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/learning/provider/section_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class TopicsListScreen extends StatefulWidget {
  final String sectionId;
  const TopicsListScreen({
    super.key,
    required this.sectionId,
  });

  @override
  State<TopicsListScreen> createState() => _TopicsListScreenState();
}

class _TopicsListScreenState extends State<TopicsListScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _fetchTopics();
    });
  }

  String _getFullImageUrl(String thumbnail) {
    if (thumbnail.startsWith('http')) {
      return thumbnail;
    } else {
      return '${baseUrl}uploads/section/$thumbnail';
    }
  }

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

    if (token != null) {
      try {
        await Provider.of<TopicProvider>(context, listen: false)
            .fetchTopics(widget.sectionId, token);
        print('Topics fetched successfully');
      } catch (e) {
        print('Error fetching topics: $e');
      }
    } else {
      print('No valid token found. User might need to log in.');
    }
  }

  @override
  Widget build(BuildContext context) {
    final sectionProvider = Provider.of<SectionProvider>(context);
    final selectedSection = sectionProvider.sections
        .firstWhere((section) => section.id == widget.sectionId);

    return Scaffold(
      backgroundColor: AppColors.bgSoftColor,
      appBar: AppBar(
        elevation: 0,
        iconTheme: const IconThemeData(color: AppColors.whiteColor),
        centerTitle: true,
        title: Text(
          selectedSection.name,
          style: AppTextStyles.whiteTextStyle.copyWith(
            fontSize: 14,
            fontWeight: FontWeight.w900,
          ),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: AppColors.gradientTheme,
          ),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(
            children: [
              Image.network(
                _getFullImageUrl(selectedSection.thumbnail),
                fit: BoxFit.cover,
                width: double.infinity,
                height: 115,
                errorBuilder: (context, error, stackTrace) {
                  print('Error loading image: $error');
                  return Container(
                    width: double.infinity,
                    height: 115,
                    color: Colors.grey[300],
                    child: Icon(
                      Icons.image_not_supported,
                      color: Colors.grey,
                    ),
                  );
                },
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Container(
                    width: 90,
                    height: 104,
                    color: Colors.grey[300],
                    child: const Center(child: CircularProgressIndicator()),
                  );
                },
              ),
              Container(
                width: double.infinity,
                height: 115,
                color: AppColors.blackColor.withOpacity(0.5),
              ),
              Center(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 42.0),
                  child: Text(
                    selectedSection.description,
                    style: AppTextStyles.whiteTextStyle.copyWith(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Consumer<TopicProvider>(
                builder: (context, topicProvider, _) {
                  if (topicProvider.topics.isEmpty) {
                    return const Center(child: CircularProgressIndicator());
                  } else if (topicProvider.error != null) {
                    return const Center(child: Text('No topics available'));
                  } else {
                    return ListView.builder(
                      itemCount: topicProvider.topics.length,
                      itemBuilder: (context, index) {
                        final topic = topicProvider.topics[index];
                        return TopicCard(
                          title: topic.name,
                          description: topic.description,
                          isCompleted: topic.isCompleted,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => LevelListScreen(
                                  topicId: topic.id,
                                  topicTitle: topic.name,
                                ),
                              ),
                            );
                          },
                        );
                      },
                    );
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
