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_theme.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) {
    // Determine Tags based on Mode
    List<String> topTags = [];
    
    if (mode == FilterChipMode.business) {
       topTags = ['Set', '甘口', '辛口', 'フルーティー', 'スパークリング'];
    } else {
       // Personal Mode: Top 15 Analysis
       final rawListAsync = ref.watch(rawSakeListItemsProvider);
       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: 8),
         child: Row(
           children: [
             // 1. CLEAR Prefecture (High Priority)
             if (selectedPrefecture != null)
               Padding(
                 padding: const EdgeInsets.only(right: 8.0),
                 child: ActionChip(
                   avatar: const Icon(LucideIcons.x, size: 16, color: Colors.white),
                   label: Text(selectedPrefecture, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                   backgroundColor: AppTheme.posimaiBlue,
                   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: const Icon(LucideIcons.x, size: 16, color: Colors.white),
                   label: Text(selectedTag, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                   backgroundColor: AppTheme.posimaiBlue,
                   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: AppTheme.posimaiBlue,
                 showCheckmark: false,
                 labelStyle: TextStyle(
                   color: (selectedTag == null && selectedPrefecture == null) ? 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) {
               return Padding(
                 padding: const EdgeInsets.only(right: 8.0),
                 child: FilterChip(
                   label: Text(tag, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
                   selected: false,
                   onSelected: (bool selected) {
                     ref.read(sakeFilterTagProvider.notifier).set(selected ? tag : null);
                   },
                 ),
               );
             }),
           ],
         ),
     );
  }
}
