import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';

class SpaceHelper {
  static SpaceModel? findSpaceByUuid(String? uuid, List<CommunityModel> communities) {
    for (var community in communities) {
      for (var space in community.spaces) {
        if (space.uuid == uuid) return space;
      }
    }
    return null;
  }

  static SpaceModel? findSpaceByInternalId(String? internalId, List<SpaceModel> spaces) {
    if (internalId != null) {
      for (var space in spaces) {
        if (space.internalId == internalId) return space;
      }
    }

    return null;
  }

  static String generateUniqueSpaceName(String originalName, List<SpaceModel> spaces) {
    final baseName = originalName.replaceAll(RegExp(r'\(\d+\)$'), '').trim();
    int maxNumber = 0;

    for (var space in spaces) {
      final match = RegExp(r'^(.*?)\((\d+)\)$').firstMatch(space.name);
      if (match != null && match.group(1)?.trim() == baseName) {
        int existingNumber = int.parse(match.group(2)!);
        if (existingNumber > maxNumber) {
          maxNumber = existingNumber;
        }
      }
    }

    return "$baseName(${maxNumber + 1})";
  }

  static bool isSave(List<SpaceModel> spaces) {
    return spaces.isNotEmpty &&
        spaces.any((space) =>
            space.status == SpaceStatus.newSpace ||
            space.status == SpaceStatus.modified ||
            space.status == SpaceStatus.deleted);
  }

  static bool isHighlightedSpace(SpaceModel space, SpaceModel? selectedSpace) {
    if (selectedSpace == null) return true;

    return space == selectedSpace ||
        selectedSpace.parent?.internalId == space.internalId ||
        selectedSpace.children?.any((child) => child.internalId == space.internalId) == true;
  }

  static bool isNameConflict(String value, SpaceModel? parentSpace, SpaceModel? editSpace) {
    final siblings = parentSpace?.children
            .where((child) => child.internalId != editSpace?.internalId)
            .toList() ??
        [];

    final editSiblings = editSpace?.parent?.children
            .where((child) => child.internalId != editSpace.internalId)
            .toList() ??
        [];

    final editSiblingConflict = editSiblings.any((child) => child.name == value);

    final siblingConflict = siblings.any((child) => child.name == value);

    final parentConflict =
        parentSpace?.name == value && parentSpace?.internalId != editSpace?.internalId;

    final parentOfEditSpaceConflict =
        editSpace?.parent?.name == value && editSpace?.parent?.internalId != editSpace?.internalId;

    final childConflict = editSpace?.children.any((child) => child.name == value) ?? false;

    return siblingConflict ||
        parentConflict ||
        editSiblingConflict ||
        parentOfEditSpaceConflict ||
        childConflict;
  }
}
