/// Widget: Brand Filter Chips
///
/// Horizontal scrolling filter chips for product brands.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/features/products/presentation/providers/product_filter_options_provider.dart';
import 'package:worker/features/products/presentation/providers/product_filters_provider.dart';

/// Brand Filter Chips Widget
///
/// Displays brands as horizontally scrolling chips.
/// Watches appliedProductFiltersProvider to show currently active filters.
/// Tapping a chip directly applies the filter (triggers API call immediately).
class BrandFilterChips extends ConsumerWidget {
  const BrandFilterChips({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    // Watch APPLIED filters to show current active state
    final appliedFilters = ref.watch(appliedProductFiltersProvider);
    final filterOptionsAsync = ref.watch(productFilterOptionsProvider);

    return filterOptionsAsync.when(
      data: (options) {
        // Add "All" option at the beginning
        final allBrands = [
          const FilterOption(value: 'all', label: 'Tất cả'),
          ...options.brands,
        ];

        return SizedBox(
          height: 48.0,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
            itemCount: allBrands.length,
            separatorBuilder: (context, index) =>
                const SizedBox(width: AppSpacing.sm),
            itemBuilder: (context, index) {
              final brand = allBrands[index];

              // "Tất cả" is selected if no brands are selected
              // A brand chip is selected if it's the ONLY brand selected
              final isSelected = brand.value == 'all'
                  ? appliedFilters.brands.isEmpty
                  : (appliedFilters.brands.length == 1 &&
                      appliedFilters.brands.contains(brand.value));

              return FilterChip(
                label: Text(
                  brand.label,
                  style: TextStyle(
                    fontSize: 14.0,
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                    color: isSelected ? Colors.white : colorScheme.onSurface,
                  ),
                ),
                selected: isSelected,
                onSelected: (selected) {
                  if (selected) {
                    // Create new filter state with only the selected brand
                    ProductFiltersState newFilters;

                    if (brand.value == 'all') {
                      // Clear brand filter, keep other filters
                      newFilters = appliedFilters.copyWith(brands: {});
                    } else {
                      // Set only this brand, keep other filters
                      newFilters = appliedFilters.copyWith(brands: {brand.value});
                    }

                    // Apply directly to trigger API call
                    ref.read(appliedProductFiltersProvider.notifier).applyFilters(newFilters);

                    // Also sync pending filters with applied
                    ref.read(productFiltersProvider.notifier).syncWithApplied();
                  }
                },
                backgroundColor: colorScheme.surface,
                selectedColor: colorScheme.primary,
                checkmarkColor: colorScheme.onPrimary,
                side: BorderSide(
                  color: isSelected ? colorScheme.primary : colorScheme.surfaceContainerHighest,
                  width: isSelected ? 2.0 : 1.0,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
                padding: const EdgeInsets.symmetric(
                  horizontal: AppSpacing.md,
                  vertical: AppSpacing.sm,
                ),
                elevation: isSelected ? AppElevation.low : 0,
                showCheckmark: false,
              );
            },
          ),
        );
      },
      loading: () => SizedBox(
        height: 48.0,
        child: Center(
          child: CustomLoadingIndicator(color: Theme.of(context).colorScheme.primary, size: 40),
        ),
      ),
      error: (error, stack) => const SizedBox.shrink(),
    );
  }
}
