import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/sake_list_provider.dart';
import '../providers/filter_providers.dart';

class PrefectureFilterSheet extends ConsumerWidget {
  const PrefectureFilterSheet({super.key});

  static Future<void> show(BuildContext context) {
    return showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => const PrefectureFilterSheet(),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Phase D6: セット商品を除外（個人モードの都道府県フィルターにセット商品の都道府県は不要）
    final rawListAsync = ref.read(allSakeItemsProvider);
    final selectedPref = ref.read(sakeFilterPrefectureProvider);

    // 1. JIS X 0401 Prefectures (North to South)
    const distinctPrefectures = [
      '北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県',
      '茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県',
      '新潟県', '富山県', '石川県', '福井県', '山梨県', '長野県', '岐阜県', '静岡県', '愛知県',
      '三重県', '滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県',
      '鳥取県', '島根県', '岡山県', '広島県', '山口県',
      '徳島県', '香川県', '愛媛県', '高知県',
      '福岡県', '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県'
    ];

    // 2. Identify available prefectures from data
    final availablePrefs = <String>{};
    if (rawListAsync.hasValue) {
      for (var item in rawListAsync.value!) {
        if (item.displayData.displayPrefecture != '不明') {
          availablePrefs.add(item.displayData.displayPrefecture);
        }
      }
    }

    // 3. Build UI List (Filter standard list by 'contains in availablePrefs')
    final sortedAvailablePrefs = distinctPrefectures
        .where((pref) => availablePrefs.contains(pref))
        .toList();
    
    // Add "All" option at the top
    final pickerItems = ['全国', ...sortedAvailablePrefs];
    
    // Initial Index
    int scrollIndex = 0;
    if (selectedPref != null) {
      final idx = pickerItems.indexOf(selectedPref);
      if (idx != -1) scrollIndex = idx;
    }

    return Container(
      height: 300,
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
      ),
      child: Column(
        children: [
          // Toolbar
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey.withValues(alpha: 0.2))),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('キャンセル', style: TextStyle(color: Colors.grey)),
                ),
                const Text('都道府県を選択', style: TextStyle(fontWeight: FontWeight.bold)),
                TextButton(
                  onPressed: () {
                    Navigator.pop(context); 
                  },
                  child: const Text('決定', style: TextStyle(fontWeight: FontWeight.bold)),
                ),
              ],
            ),
          ),
          // Picker
          Expanded(
            child: CupertinoPicker(
              itemExtent: 40,
              scrollController: FixedExtentScrollController(initialItem: scrollIndex),
              onSelectedItemChanged: (index) {
                final value = pickerItems[index];
                // Haptic Feedback for "Rolling" feel
                HapticFeedback.selectionClick();
                
                ref.read(sakeFilterPrefectureProvider.notifier).set(
                  value == '全国' ? null : value
                );
              },
              children: pickerItems.map((pref) => Center(
                child: Text(
                  pref,
                  style: TextStyle(
                    color: Theme.of(context).textTheme.bodyLarge?.color,
                    fontSize: 18,
                  ),
                ),
              )).toList(),
            ),
          ),
        ],
      ),
    );
  }
}
