/// 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/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.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.
/// Synced with filter drawer - both use productFiltersProvider.brands.
/// Chips are single-select (tapping a brand clears others and sets just that one).
class BrandFilterChips extends ConsumerWidget {
  const BrandFilterChips({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final filtersState = ref.watch(productFiltersProvider);
    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'
                  ? filtersState.brands.isEmpty
                  : (filtersState.brands.length == 1 &&
                      filtersState.brands.contains(brand.value));

              return FilterChip(
                label: Text(
                  brand.label,
                  style: TextStyle(
                    fontSize: 14.0,
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                    color: isSelected ? AppColors.white : AppColors.grey900,
                  ),
                ),
                selected: isSelected,
                onSelected: (selected) {
                  if (selected) {
                    final notifier = ref.read(productFiltersProvider.notifier);

                    if (brand.value == 'all') {
                      // Clear all brand filters
                      // Reset all brands by setting to empty set
                      final currentBrands = List<String>.from(filtersState.brands);
                      for (final b in currentBrands) {
                        notifier.toggleBrand(b); // Toggle off each brand
                      }
                    } else {
                      // Single-select: clear all other brands and set only this one
                      final currentBrands = List<String>.from(filtersState.brands);

                      // First, clear all existing brands
                      for (final b in currentBrands) {
                        notifier.toggleBrand(b);
                      }

                      // Then add the selected brand
                      notifier.toggleBrand(brand.value);
                    }
                  }
                },
                backgroundColor: AppColors.white,
                selectedColor: AppColors.primaryBlue,
                checkmarkColor: AppColors.white,
                side: BorderSide(
                  color: isSelected ? AppColors.primaryBlue : AppColors.grey100,
                  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: () => const SizedBox(
        height: 48.0,
        child: Center(
          child: CircularProgressIndicator(strokeWidth: 2.0),
        ),
      ),
      error: (error, stack) => const SizedBox.shrink(),
    );
  }
}
