import 'package:flutter/material.dart';

import '../../../shared/layout/adaptive_card_grid.dart';
import '../../../shared/widgets/section_header.dart';
import 'aggregated_media_card.dart';
import '../aggregated_grouping.dart';


List<Widget> buildAggregatedGridSlivers({
  required List<AggregatedGroup> groups,
  required Set<String> collapsed,
  required ValueChanged<String> onToggle,
  required Widget Function(AggregatedEntry entry) cardBuilder,
  EdgeInsets padding = const EdgeInsets.fromLTRB(24, 4, 24, 24),
}) {
  final slivers = <Widget>[];
  for (final group in groups) {
    final isCollapsed = collapsed.contains(group.key);
    slivers.add(
      SliverToBoxAdapter(
        child: Padding(
          padding: EdgeInsets.only(left: padding.left, right: padding.right),
          child: SectionHeader(
            label: group.label,
            count: group.entries.length,
            collapsible: true,
            collapsed: isCollapsed,
            onToggle: () => onToggle(group.key),
          ),
        ),
      ),
    );
    if (!isCollapsed) {
      final entries = group.entries;
      slivers.add(
        SliverPadding(
          padding: EdgeInsets.fromLTRB(padding.left, 0, padding.right, 20),
          sliver: SliverLayoutBuilder(
            builder: (context, constraints) {
              final availableWidth = constraints.crossAxisExtent;
              final columnCount = cardColumnsFor(
                availableWidth,
                minCardWidth: kRichCardMinWidth,
              );
              final gapTotalWidth = kCardGap * (columnCount - 1);
              final cardWidth = (availableWidth - gapTotalWidth) / columnCount;

              return SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: columnCount,
                  mainAxisExtent: AggregatedMediaCard.height,
                  crossAxisSpacing: kCardGap,
                  mainAxisSpacing: kCardGap,
                ),
                delegate: SliverChildBuilderDelegate(
                  (context, index) => SizedBox(
                    width: cardWidth,
                    child: cardBuilder(entries[index]),
                  ),
                  childCount: entries.length,
                ),
              );
            },
          ),
        ),
      );
    }
  }
  return slivers;
}
