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

import '../../models/sake_item.dart';
import '../../providers/sake_list_provider.dart'; // For sakeOrderControllerProvider
import '../../providers/ui_experiment_provider.dart'; // A/B Test
import 'sake_grid_item.dart';

class SakeGridView extends ConsumerWidget {
  final List<dynamic> sakeList; // Accepts List<dynamic> from AsyncValue but cast internal
  final bool isMenuMode;
  final bool enableReorder;

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

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

    final experiment = ref.watch(uiExperimentProvider);

    // If reorder is disabled (Menu Creation Screen), use standard GridView
    if (!enableReorder || isMenuMode) {
      return GridView.builder(
        padding: const EdgeInsets.all(4),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: experiment.gridColumns,
          crossAxisSpacing: 1, // Minimized spacing for denser layout
          mainAxisSpacing: 1, // Minimized spacing for denser layout
          childAspectRatio: experiment.gridColumns == 3 ? (1.0 / 1.5) : 1.0,
        ),
        itemCount: list.length,
        itemBuilder: (context, index) {
          final sake = list[index];
          return SakeGridItem(
            sake: sake,
            isMenuMode: isMenuMode,
          );
        },
      );
    }

    // Standard ReorderableGridView for Home Screen
    return ReorderableGridView.builder(
      padding: const EdgeInsets.all(4),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: experiment.gridColumns,
        crossAxisSpacing: 1, // Minimized spacing for denser layout
        mainAxisSpacing: 1, // Minimized spacing for denser layout
        childAspectRatio: experiment.gridColumns == 3 ? (1.0 / 1.5) : 1.0,
      ),
      itemCount: list.length,
      onReorder: (oldIndex, newIndex) {
        final item = list.removeAt(oldIndex);
        list.insert(newIndex, item);

        // Update via Provider (Normal Mode - Global Sort)
        ref.read(sakeOrderControllerProvider.notifier).updateOrder(list);
        HapticFeedback.lightImpact();
      },
      itemBuilder: (context, index) {
         final sake = list[index];
         return KeyedSubtree(
           key: ValueKey(sake.id),
           child: SakeGridItem(
             sake: sake,
             isMenuMode: isMenuMode,
           ),
         );
      },
    );
  }
}
