import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/core/widgets/loading/shimmer_loading_widget.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/modules/topics/widgets/topic_card_loading.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}api/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.');
    }
  }

  // Tambahkan method baru di dalam _TopicsListScreenState
  void _showSectionDescriptionDialog(BuildContext context, String description) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              color: AppColors.whiteColor,
              shape: BoxShape.rectangle,
              boxShadow: const [
                BoxShadow(
                  color: Colors.black26,
                  blurRadius: 10.0,
                  offset: Offset(0.0, 10.0),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: double.infinity,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        vertical: 16, horizontal: 16),
                    decoration: const BoxDecoration(
                      color: AppColors.blueColor,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(16),
                        topRight: Radius.circular(16),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        'Section Description',
                        style: AppTextStyles.whiteTextStyle.copyWith(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),

                // Content
                Flexible(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(24),
                    child: Text(
                      description,
                      style: AppTextStyles.greyTextStyle.copyWith(
                        fontSize: 13,
                        fontWeight: FontWeight.w300,
                        height: 1.5,
                      ),
                      textAlign: TextAlign.justify,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.symmetric(
                          vertical: 12, horizontal: 20),
                    ),
                    onPressed: () => Navigator.of(context).pop(),
                    icon: const Icon(Icons.close, color: Colors.white),
                    label: const Text(
                      'Close',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @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,
          ),
          textAlign: TextAlign.center,
        ),
        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: 140,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: double.infinity,
                    height: 140,
                    color: Colors.grey[300],
                    child: const Icon(
                      Icons.image_not_supported,
                      color: Colors.grey,
                    ),
                  );
                },
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return const ShimmerLoadingWidget(
                    height: 140,
                    width: double.infinity,
                  );
                },
              ),
              Container(
                width: double.infinity,
                height: 140,
                color: AppColors.blackColor.withOpacity(0.7),
              ),
              Center(
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 32.0),
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 8.0),
                          child: Text(
                            selectedSection.description,
                            style: AppTextStyles.whiteTextStyle.copyWith(
                              fontSize: 13,
                              fontWeight: FontWeight.w500,
                            ),
                            textAlign: TextAlign.center,
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(height: 8),
                        GestureDetector(
                          onTap: () => _showSectionDescriptionDialog(
                              context, selectedSection.description),
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                                vertical: 8, horizontal: 16),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.2),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              'Read More',
                              style: AppTextStyles.whiteTextStyle.copyWith(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: Colors.white.withOpacity(0.8),
                                decoration: TextDecoration.underline,
                                decorationColor: Colors.white.withOpacity(0.8),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
          // const SizedBox(height: 12),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Consumer<TopicProvider>(
                builder: (context, topicProvider, _) {
                  if (topicProvider.isLoading) {
                    return ListView.builder(
                      padding: const EdgeInsets.only(top: 8),
                      itemCount: 6,
                      itemBuilder: (context, index) => const TopicCardLoading(),
                    );
                  }

                  if (topicProvider.error != null) {
                    return Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            'Failed to load topics',
                            style: AppTextStyles.greyTextStyle,
                          ),
                          const SizedBox(height: 16),
                          ElevatedButton(
                            onPressed: _fetchTopics,
                            child: const Text('Retry'),
                          ),
                        ],
                      ),
                    );
                  }

                  if (topicProvider.topics.isEmpty) {
                    return Center(
                      child: Text(
                        'No topics available',
                        style: AppTextStyles.greyTextStyle,
                      ),
                    );
                  }

                  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,
                              ),
                            ),
                          );
                        },
                      );
                    },
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
