import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/home/models/completed_topics_model.dart';
import 'package:english_learning/features/home/widgets/progress_bar.dart';
import 'package:english_learning/features/learning/modules/topics/screens/topics_list_screen.dart';
import 'package:english_learning/features/learning/provider/section_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProgressCard extends StatelessWidget {
  final List<CompletedTopic> completedTopic;

  const ProgressCard({super.key, required this.completedTopic});

  String _getFullImageUrl(String thumbnail) {
    return thumbnail.startsWith('http')
        ? thumbnail
        : '${baseUrl}api/uploads/section/$thumbnail';
  }

  Future<void> _navigateToTopics(
      BuildContext context, CompletedTopic topic) async {
    // Get the SectionProvider
    final sectionProvider =
        Provider.of<SectionProvider>(context, listen: false);

    // Show loading indicator while checking/loading data
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      // If sections aren't loaded yet, load them
      if (sectionProvider.sections.isEmpty) {
        final userProvider = Provider.of<UserProvider>(context, listen: false);
        final token = await userProvider.getValidToken();

        if (token != null) {
          await sectionProvider.fetchSections(token);
        } else {
          throw Exception('No valid token found');
        }
      }

      // Remove loading indicator
      Navigator.pop(context);

      // Navigate to topics screen
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TopicsListScreen(
            sectionId: topic.idSection,
          ),
        ),
      );
    } catch (e) {
      // Remove loading indicator
      Navigator.pop(context);

      // Show error dialog
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('Error'),
          content: const Text(
              'Unable to load section data. Please try again later.'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('OK'),
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ...completedTopic.asMap().entries.map(
          (entry) {
            CompletedTopic topic = entry.value;
            return Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: _buildTopicItem(context, topic),
            );
          },
        ),
      ],
    );
  }

  Widget _buildTopicItem(BuildContext context, CompletedTopic topic) {
    return GestureDetector(
      onTap: () => _navigateToTopics(context, topic),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  _getFullImageUrl(topic.thumbnail ?? ''),
                  width: 90,
                  height: 130,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: 90,
                      height: 130,
                      color: Colors.grey[300],
                      child: const Icon(
                        Icons.image_not_supported,
                        color: Colors.grey,
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      topic.nameSection,
                      style: AppTextStyles.blackTextStyle.copyWith(
                        fontSize: 16,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      topic.descriptionSection,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: AppTextStyles.disableTextStyle.copyWith(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 24),
                    ProgressBar(
                      completedTopics: topic.completedTopics,
                      totalTopics: topic.totalTopics,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
