import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/flexible_item_widget.dart';

import 'package:syncrow_web/utils/color_manager.dart';

class DynamicProductWidget extends StatelessWidget {
  final Map<String, int> productTagCount;
  final double maxWidth;
  final double maxHeight;

  const DynamicProductWidget({
    Key? key,
    required this.productTagCount,
    required this.maxWidth,
    required this.maxHeight,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const double itemSpacing = 8.0;
    const double lineSpacing = 8.0;
    const double textPadding = 16.0;
    const double itemHeight = 40.0;

    List<Widget> productWidgets = [];
    double currentLineWidth = 0.0;
    double currentHeight = itemHeight;

    for (final product in productTagCount.entries) {
      final String prodType = product.key;
      final int count = product.value;

      final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: 'x$count',
          style: Theme.of(context)
              .textTheme
              .bodySmall
              ?.copyWith(color: ColorsManager.spaceColor),
        ),
        textDirection: TextDirection.ltr,
      )..layout();

      final double itemWidth = textPainter.width + textPadding + 20;

      if (currentLineWidth + itemWidth + itemSpacing > maxWidth) {
        currentHeight += itemHeight + lineSpacing;
        if (currentHeight > maxHeight) {
          productWidgets.add(const EllipsisItemWidget());
          break;
        }
        currentLineWidth = 0.0;
      }

      productWidgets.add(FlexibleItemWidget(prodType: prodType, count: count));
      currentLineWidth += itemWidth + itemSpacing;
    }

    return Wrap(
      spacing: itemSpacing,
      runSpacing: lineSpacing,
      children: productWidgets,
    );
  }
}
