/// Category Filter Chips Widget
///
/// Horizontal scrollable list of category filter chips.
/// Used in news list page for filtering articles by category.
/// Fetches categories dynamically from the Frappe API.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/features/news/domain/entities/blog_category.dart';
import 'package:worker/features/news/presentation/providers/news_provider.dart';

/// Category Filter Chips
///
/// Displays a horizontal scrollable row of filter chips for news categories.
/// Features:
/// - "Tất cả" (All) option to show all categories
/// - Dynamic categories from Frappe API (Tin tức, Chuyên môn, Dự án, Khuyến mãi)
/// - Active state styling (primary blue background, white text)
/// - Inactive state styling (grey background, grey text)
/// - Loading state with shimmer effect
/// - Error state with retry button
class CategoryFilterChips extends ConsumerWidget {
  /// Currently selected category name (null = All)
  final String? selectedCategoryName;

  /// Callback when a category is tapped (passes category name)
  final void Function(String? categoryName) onCategorySelected;

  /// Constructor
  const CategoryFilterChips({
    super.key,
    required this.selectedCategoryName,
    required this.onCategorySelected,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final categoriesAsync = ref.watch(blogCategoriesProvider);

    return categoriesAsync.when(
      data: (categories) => _buildCategoryChips(context, categories),
      loading: () => _buildLoadingState(context),
      error: (error, stack) => _buildErrorState(context, error, ref),
    );
  }

  /// Build category chips with data
  Widget _buildCategoryChips(BuildContext context, List<BlogCategory> categories) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // "Tất cả" chip
          _buildCategoryChip(
            context,
            label: 'Tất cả',
            isSelected: selectedCategoryName == null,
            onTap: () => onCategorySelected(null),
          ),

          const SizedBox(width: AppSpacing.sm),

          // Dynamic category chips from API
          ...categories.map((category) {
            return Padding(
              padding: const EdgeInsets.only(right: AppSpacing.sm),
              child: _buildCategoryChip(
                context,
                label: category.title,
                isSelected: selectedCategoryName == category.name,
                onTap: () => onCategorySelected(category.name),
              ),
            );
          }),
        ],
      ),
    );
  }

  /// Build loading state with shimmer placeholders
  Widget _buildLoadingState(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: List.generate(5, (index) {
          return Padding(
            padding: const EdgeInsets.only(right: AppSpacing.sm),
            child: Container(
              width: 80,
              height: 32,
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerHighest,
                borderRadius: BorderRadius.circular(24),
              ),
            ),
          );
        }),
      ),
    );
  }

  /// Build error state with retry
  Widget _buildErrorState(BuildContext context, Object error, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: AppSpacing.md,
              vertical: AppSpacing.sm,
            ),
            decoration: BoxDecoration(
              color: colorScheme.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(24),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                FaIcon(FontAwesomeIcons.circleExclamation, size: 16, color: colorScheme.onSurfaceVariant),
                const SizedBox(width: AppSpacing.xs),
                Text(
                  'Lỗi tải danh mục',
                  style: TextStyle(
                    fontSize: 14,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
                const SizedBox(width: AppSpacing.xs),
                GestureDetector(
                  onTap: () => ref.refresh(blogCategoriesProvider),
                  child: FaIcon(FontAwesomeIcons.arrowsRotate, size: 14, color: colorScheme.primary),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Build individual category chip
  Widget _buildCategoryChip(
    BuildContext context, {
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: AppSpacing.md,
          vertical: AppSpacing.sm,
        ),
        decoration: BoxDecoration(
          color: isSelected ? colorScheme.primary : colorScheme.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(24),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: isSelected ? colorScheme.onPrimary : colorScheme.onSurfaceVariant,
          ),
        ),
      ),
    );
  }
}
