import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/learning/provider/section_provider.dart';
import 'package:english_learning/features/learning/widgets/section_card.dart';
import 'package:english_learning/features/learning/modules/topics/screens/topics_list_screen.dart';
import 'package:english_learning/features/learning/widgets/section_card_loading.dart';
import 'package:flutter/material.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:provider/provider.dart';

class LearningScreen extends StatefulWidget {
  const LearningScreen({super.key});

  @override
  State<LearningScreen> createState() => _LearningScreenState();
}

class _LearningScreenState extends State<LearningScreen>
    with AutomaticKeepAliveClientMixin {
  bool _isInitialLoading = true;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _initializeSections();
  }

  Future<void> _initializeSections() async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final sectionProvider =
        Provider.of<SectionProvider>(context, listen: false);

    // Cek apakah sections sudah ada
    if (sectionProvider.sections.isEmpty) {
      try {
        final token = await userProvider.getValidToken();
        if (token != null) {
          await sectionProvider.fetchSections(token);
        }
      } catch (e) {
        print('Error initializing sections: $e');
      } finally {
        setState(() {
          _isInitialLoading = false;
        });
      }
    } else {
      setState(() {
        _isInitialLoading = false;
      });
    }
  }

  Future<void> _refreshSections() async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final sectionProvider =
        Provider.of<SectionProvider>(context, listen: false);

    try {
      final token = await userProvider.getValidToken();
      if (token != null) {
        await sectionProvider.fetchSections(token);
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to refresh sections: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: AppColors.bgSoftColor,
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.only(top: 28.0, left: 16.0, right: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Choose what you want to learn!',
                style: AppTextStyles.blueTextStyle.copyWith(
                  fontSize: 18,
                  fontWeight: FontWeight.w900,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                'Develop your English skills by studying the topics in each section below.',
                style: AppTextStyles.greyTextStyle.copyWith(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 15),
              Expanded(
                child: Consumer<SectionProvider>(
                  builder: (context, sectionProvider, _) {
                    // Prioritaskan loading state
                    if (_isInitialLoading || sectionProvider.isLoading) {
                      return ListView.builder(
                        padding: const EdgeInsets.only(top: 8),
                        itemCount: 4,
                        itemBuilder: (context, index) =>
                            const SectionCardLoading(),
                      );
                    }

                    // Tampilkan error jika ada
                    if (sectionProvider.error != null) {
                      return RefreshIndicator(
                        onRefresh: _refreshSections,
                        child: ListView(
                          children: [
                            Center(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    'Error: ${sectionProvider.error}',
                                    style: AppTextStyles.greyTextStyle,
                                  ),
                                  const SizedBox(height: 16),
                                  ElevatedButton(
                                    onPressed: _refreshSections,
                                    child: const Text('Retry'),
                                  )
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    }

                    // Tampilkan sections atau pesan jika kosong
                    if (sectionProvider.sections.isEmpty) {
                      return RefreshIndicator(
                        onRefresh: _refreshSections,
                        child: ListView(
                          children: [
                            Center(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(
                                    Icons.library_books_outlined,
                                    size: 80,
                                    color: Colors.grey,
                                  ),
                                  const SizedBox(height: 16),
                                  Text(
                                    'No sections available',
                                    style: AppTextStyles.greyTextStyle.copyWith(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  const SizedBox(height: 16),
                                  ElevatedButton(
                                    onPressed: _refreshSections,
                                    child: const Text('Refresh'),
                                  )
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    }

                    // Tampilkan daftar sections
                    return RefreshIndicator(
                      onRefresh: _refreshSections,
                      child: ListView.builder(
                        itemCount: sectionProvider.sections.length,
                        itemBuilder: (context, index) {
                          final section = sectionProvider.sections[index];
                          return SectionCard(
                            section: section,
                            onTap: () => Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => TopicsListScreen(
                                  sectionId: section.id,
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
