import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/room_name_widget.dart';

class DynamicRoomWidget extends StatelessWidget {
  final List<SubspaceTemplateModel>? subspaceModels;
  final double maxWidth;
  final double maxHeight;

  const DynamicRoomWidget({
    Key? key,
    required this.subspaceModels,
    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 = 30.0;

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

    for (final subspace in subspaceModels!) {
      final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: subspace.subspaceName,
          style: Theme.of(context).textTheme.bodyMedium
        ),
        textDirection: TextDirection.ltr,
      )..layout();

      final double itemWidth = textPainter.width + textPadding;

      if (currentLineWidth + itemWidth + itemSpacing > maxWidth) {
        currentHeight += itemHeight + lineSpacing;
        if (currentHeight > maxHeight) {
          roomWidgets.add(const RoomNameWidget(name: "..."));
          break;
        }
        currentLineWidth = 0.0;
      }

      roomWidgets.add(RoomNameWidget(name: subspace.subspaceName));
      currentLineWidth += itemWidth + itemSpacing;
    }

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