import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:english_learning/core/widgets/global_button.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/history/provider/history_provider.dart';
import 'package:english_learning/features/history/widgets/custom_tab_bar.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/history/widgets/exercise_history_card.dart';
import 'package:english_learning/features/home/screens/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

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

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  bool _isInitialLoading = true;

  bool get wantKeepAlive => true;

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

  Future<void> _initializeHistory() async {
    final historyProvider =
        Provider.of<HistoryProvider>(context, listen: false);
    final userProvider = Provider.of<UserProvider>(context, listen: false);

    try {
      await historyProvider.fetchLearningHistory(userProvider.jwtToken!);
    } catch (e) {
      print('Error initializing history: $e');
    } finally {
      setState(() {
        _isInitialLoading = false;
      });
    }
  }

  Future<void> _refreshHistory() async {
    final historyProvider =
        Provider.of<HistoryProvider>(context, listen: false);
    final userProvider = Provider.of<UserProvider>(context, listen: false);

    try {
      await historyProvider.fetchLearningHistory(userProvider.jwtToken!);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to refresh history: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  // Tambahkan method untuk shimmer loading
  Widget _buildShimmerLoading() {
    return ListView.builder(
      itemCount: 5,
      itemBuilder: (context, index) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
          child: Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[100]!,
            child: Container(
              width: double.infinity,
              height: 100,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                gradient: LinearGradient(
                  colors: [
                    Colors.grey[200]!,
                    Colors.grey[100]!,
                    Colors.grey[200]!,
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  bool isNotFoundError(String error) {
    return error.toLowerCase().contains('no learning history found') ||
        error.toLowerCase().contains('not found');
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<HistoryProvider>(
      builder: (context, historyProvider, child) {
        return Scaffold(
          backgroundColor: AppColors.bgSoftColor,
          body: SafeArea(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 30.0,
                ),
                child: Column(
                  children: [
                    _buildHeader(),
                    const SizedBox(height: 8),
                    const CustomTabBar(),
                    const SizedBox(height: 8),
                    Expanded(
                      child: _buildContent(context, historyProvider),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildContent(BuildContext context, HistoryProvider historyProvider) {
    // Prioritaskan initial loading
    if (_isInitialLoading || historyProvider.isLoading) {
      return _buildShimmerLoading();
    }

    // Tangani error
    if (historyProvider.error != null) {
      return isNotFoundError(historyProvider.error!)
          ? _buildEmptyState(context)
          : _buildErrorState(context, historyProvider.error!);
    }

    // Tampilkan empty state jika tidak ada history
    if (historyProvider.learningHistory.isEmpty) {
      return _buildEmptyState(context);
    }

    // Tampilkan daftar history dengan refresh indicator
    return RefreshIndicator(
      onRefresh: _refreshHistory,
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        child: ListView.builder(
          key: ValueKey(historyProvider.learningHistory.length),
          itemCount: historyProvider.learningHistory.length,
          itemBuilder: (context, index) {
            return AnimatedOpacity(
              opacity: 1.0,
              duration: const Duration(milliseconds: 500),
              child: Column(
                children: [
                  ExerciseHistoryCard(
                    exercise: historyProvider.learningHistory[index],
                  ),
                  const SizedBox(height: 8.0),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: AppColors.whiteColor,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Your Exercise History!',
            style: AppTextStyles.blueTextStyle.copyWith(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Track your progress with a personalized overview of all your workouts.',
            style: AppTextStyles.greyTextStyle.copyWith(
              fontSize: 13,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorState(BuildContext context, String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            BootstrapIcons.exclamation_diamond_fill,
            color: AppColors.blueColor,
            size: 82,
          ),
          const SizedBox(height: 16),
          Text(
            'Error: $error',
            style: AppTextStyles.redTextStyle.copyWith(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          GlobalButton(
            onPressed: () {
              final historyProvider =
                  Provider.of<HistoryProvider>(context, listen: false);
              final userProvider =
                  Provider.of<UserProvider>(context, listen: false);
              historyProvider.refreshData(userProvider.jwtToken!);
            },
            text: 'Try Again',
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: AppColors.whiteColor,
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'Still New?',
              style: AppTextStyles.blackTextStyle.copyWith(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              'Begin your journey!',
              style: AppTextStyles.disableTextStyle.copyWith(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 16),
            SvgPicture.asset(
              'lib/features/history/assets/images/is_empty_illustration.svg',
              width: 160,
            ),
            const SizedBox(height: 32),
            GlobalButton(
              text: 'Explore',
              backgroundColor: AppColors.yellowButtonColor,
              textColor: AppColors.blackColor,
              onPressed: () {
                HomeScreen.navigateToTab(context, 1);
              },
            ),
          ],
        ),
      ),
    );
  }
}
