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/learning/provider/section_provider.dart';
import 'package:flutter/material.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:provider/provider.dart';

class CustomTabBar extends StatelessWidget {
  const CustomTabBar({super.key});

  @override
  Widget build(BuildContext context) {
    final historyProvider = Provider.of<HistoryProvider>(context);
    final sectionProvider = Provider.of<SectionProvider>(context);
    final selectedPageIndex = historyProvider.selectedPageIndex;

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: sectionProvider.sections.asMap().entries.map((entry) {
          int index = entry.key;
          String sectionName = entry.value.name;
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 4.0),
            child: _TabBarButton(
              title: sectionName,
              isSelected: selectedPageIndex == index,
              onTap: () => _setSelectedPageIndex(context, index),
            ),
          );
        }).toList(),
      ),
    );
  }

  void _setSelectedPageIndex(BuildContext context, int index) {
    final historyProvider =
        Provider.of<HistoryProvider>(context, listen: false);
    final userProvider = Provider.of<UserProvider>(context, listen: false);

    historyProvider.setSelectedPageIndex(index);
    historyProvider.fetchLearningHistory(userProvider.jwtToken!);
  }
}

class _TabBarButton extends StatelessWidget {
  final String title;
  final bool isSelected;
  final VoidCallback onTap;

  const _TabBarButton({
    required this.title,
    required this.isSelected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.blueColor : AppColors.whiteColor,
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Text(
          title,
          style: TextStyle(
            color: isSelected ? AppColors.whiteColor : AppColors.disableColor,
            fontWeight: isSelected ? FontWeight.w900 : FontWeight.normal,
          ),
        ),
      ),
    );
  }
}
