import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/sake_list_provider.dart';
import '../../providers/filter_providers.dart';
import '../../theme/app_colors.dart';
import 'package:lucide_icons/lucide_icons.dart';

enum FilterChipMode {
  personal,
  business,
}

class SakeFilterChips extends ConsumerWidget {
  final FilterChipMode mode;
  const SakeFilterChips({super.key, this.mode = FilterChipMode.personal});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final appColors = Theme.of(context).extension<AppColors>()!;
    // Determine Tags based on Mode
    List<String> topTags = [];
    
    if (mode == FilterChipMode.business) {
       topTags = ['Set', '甘口', '辛口', 'フルーティー', 'スパークリング'];
    } else {
       // Personal Mode: Top 15 Analysis
       // Phase D6: セット商品を除外（個人モードのタグフィルターにセット商品のタグは不要）
       final rawListAsync = ref.watch(allSakeItemsProvider);
       final Map<String, int> tagFrequency = {};
       if (rawListAsync.hasValue) {
          for (var item in rawListAsync.value!) {
             for (var tag in item.hiddenSpecs.flavorTags) {
               tagFrequency[tag] = (tagFrequency[tag] ?? 0) + 1;
             }
          }
       }
       final popularTags = tagFrequency.entries.toList()..sort((a, b) => b.value.compareTo(a.value));
       topTags = popularTags.take(15).map((e) => e.key).toList();
    }

    final selectedTag = ref.watch(sakeFilterTagProvider);
    final selectedPrefecture = ref.watch(sakeFilterPrefectureProvider);
     
    // If selected tag is not in list (e.g. searching or custom), add it
    if (selectedTag != null && selectedTag != 'All' && !topTags.contains(selectedTag)) {
       topTags.insert(0, selectedTag);
    }
     
    final colorScheme = Theme.of(context).colorScheme;

    return SingleChildScrollView(
         scrollDirection: Axis.horizontal,
         padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), // Minimized vertical padding
         child: Row(
           children: [
             // 1. CLEAR Prefecture (High Priority)
             if (selectedPrefecture != null)
               Padding(
                 padding: const EdgeInsets.only(right: 8.0),
                 child: ActionChip(
                   avatar: Icon(LucideIcons.x, size: 16, color: appColors.surfaceSubtle),
                   label: Text(selectedPrefecture, style: TextStyle(color: appColors.surfaceSubtle, fontWeight: FontWeight.bold)),
                   backgroundColor: appColors.brandPrimary,
                   onPressed: () => ref.read(sakeFilterPrefectureProvider.notifier).set(null),
                 ),
               ),

             // 2. CLEAR Tag (High Priority)
             if (selectedTag != null && selectedTag != 'All')
               Padding(
                 padding: const EdgeInsets.only(right: 8.0),
                 child: ActionChip(
                   avatar: Icon(LucideIcons.x, size: 16, color: appColors.surfaceSubtle),
                   label: Text(selectedTag, style: TextStyle(color: appColors.surfaceSubtle, fontWeight: FontWeight.bold)),
                   backgroundColor: appColors.brandPrimary,
                   onPressed: () => ref.read(sakeFilterTagProvider.notifier).set(null),
                 ),
               ),

             // 3. "All" Button (Business Mode Explicit "All", Personal Implicit Reset)
             // In Business Mode, "All" clears filters.
             Padding(
               padding: const EdgeInsets.only(right: 8.0),
               child: FilterChip(
                 label: const Text('All'),
                 selected: selectedTag == null && selectedPrefecture == null,
                 selectedColor: Theme.of(context).brightness == Brightness.dark
                     ? colorScheme.primary  // #8AB4F6 (lighter blue for dark mode)
                     : Theme.of(context).primaryColor, // Sumi/Kohaku for light mode
                 showCheckmark: false,
                 side: (selectedTag == null && selectedPrefecture == null)
                     ? BorderSide(
                         color: Theme.of(context).brightness == Brightness.dark
                             ? colorScheme.primary
                             : Theme.of(context).primaryColor,
                         width: 1.5,
                       )
                     : null,
                 labelStyle: TextStyle(
                   color: (selectedTag == null && selectedPrefecture == null)
                       ? (Theme.of(context).brightness == Brightness.dark ? Colors.black : Colors.white)
                       : colorScheme.onSurface,
                   fontWeight: FontWeight.bold,
                   fontSize: 13,
                 ),
                 onSelected: (_) {
                   ref.read(sakeFilterTagProvider.notifier).set(null);
                   ref.read(sakeFilterPrefectureProvider.notifier).set(null);
                 },
               ),
             ),

             // 4. Tag List
             ...topTags.where((t) => t != selectedTag).map((tag) {
               final isDark = Theme.of(context).brightness == Brightness.dark;
               return Padding(
                 padding: const EdgeInsets.only(right: 8.0),
                 child: FilterChip(
                   label: Text(
                     tag,
                     style: TextStyle(
                       fontWeight: FontWeight.bold,
                       fontSize: 13,
                       color: isDark ? appColors.textPrimary : colorScheme.onSurface,
                     ),
                   ),
                   selected: false,
                   backgroundColor: isDark
                       ? appColors.surfaceSubtle
                       : null,
                   side: BorderSide(
                     color: isDark
                         ? appColors.divider
                         : colorScheme.outline.withValues(alpha: 0.5),
                     width: 1,
                   ),
                   onSelected: (bool selected) {
                     ref.read(sakeFilterTagProvider.notifier).set(selected ? tag : null);
                   },
                 ),
               );
             }),
           ],
         ),
     );
  }
}
