import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/services.dart'; // HapticFeedback

import '../../models/sake_item.dart';
import '../../providers/sake_list_provider.dart';
import 'sake_list_item.dart';

class SakeListView extends ConsumerWidget {
  final List<dynamic> sakeList;
  final bool isMenuMode;
  final bool enableReorder;

  const SakeListView({
    super.key,
    required this.sakeList,
    required this.isMenuMode,
    this.enableReorder = false,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Dynamic cast for Hive list
    final list = sakeList.cast<SakeItem>();

    // If reorder is disabled or in Menu Mode, use standard ListView
    if (!enableReorder || isMenuMode) {
        return ListView.builder(
           padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
           itemCount: list.length,
           itemBuilder: (context, index) {
              return Padding(
                padding: const EdgeInsets.only(bottom: 4),
                child: SakeListItem(
                  sake: list[index],
                  isMenuMode: isMenuMode,
                  index: null, // No drag handle
                ),
              );
           }
        );
    }

    // Standard ReorderableListView for Home Screen
    return ReorderableListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
      itemCount: list.length,
      onReorder: (oldIndex, newIndex) {
         if (oldIndex < newIndex) {
            newIndex -= 1;
         }
         // Perform Reorder locally
         final item = list.removeAt(oldIndex);
         list.insert(newIndex, item);
         // Update Order via Controller (Normal Mode - Global Sort)
         ref.read(sakeOrderControllerProvider.notifier).updateOrder(list);

         // Haptic
         HapticFeedback.lightImpact();
      },
      proxyDecorator: (widget, index, animation) {
         return Material(
           elevation: 4,
           color: Colors.transparent,
           child: widget,
         );
      },
      itemBuilder: (context, index) {
        final sake = list[index];
        return Padding(
           key: ValueKey(sake.id),
           padding: const EdgeInsets.only(bottom: 4),
           child: SakeListItem(
             sake: sake,
             isMenuMode: isMenuMode,
             index: index // For drag handle
           ),
        );
      },
    );
  }
}
