import 'package:uuid/uuid.dart';

class Group {
  final String id;
  final String name;
  final String description;
  final String? iconUrl;
  final String createdBy;
  final DateTime createdAt;
  final bool isDefault;
  final bool isPublic;
  final int memberCount;

  Group({
    String? id,
    required this.name,
    required this.description,
    this.iconUrl,
    required this.createdBy,
    DateTime? createdAt,
    this.isDefault = false,
    this.isPublic = true,
    this.memberCount = 0,
  }) : id = id ?? const Uuid().v4(),
       createdAt = createdAt ?? DateTime.now();

  // Create a copy of this group
  Group copyWith({
    String? id,
    String? name,
    String? description,
    String? iconUrl,
    String? createdBy,
    DateTime? createdAt,
    bool? isDefault,
    bool? isPublic,
    int? memberCount,
  }) {
    return Group(
      id: id ?? this.id,
      name: name ?? this.name,
      description: description ?? this.description,
      iconUrl: iconUrl ?? this.iconUrl,
      createdBy: createdBy ?? this.createdBy,
      createdAt: createdAt ?? this.createdAt,
      isDefault: isDefault ?? this.isDefault,
      isPublic: isPublic ?? this.isPublic,
      memberCount: memberCount ?? this.memberCount,
    );
  }

  // Create from database Map
  factory Group.fromMap(Map<String, dynamic> map) {
    // Ensure we have a valid UUID string for id
    String idValue;
    if (map['id'] is String) {
      idValue = map['id'] as String;
    } else {
      // Fallback to a valid UUID if id is not a string or is missing
      idValue = const Uuid().v4();
    }

    final createdAtStr = map['created_at'] as String?;
    final DateTime createdAt =
        createdAtStr != null ? DateTime.parse(createdAtStr) : DateTime.now();

    return Group(
      id: idValue,
      name: map['name'] as String,
      description: map['description'] as String? ?? '',
      iconUrl: map['icon_url'] as String?,
      createdBy: map['created_by'] as String,
      createdAt: createdAt,
      isDefault: map['is_default'] as bool? ?? false,
      isPublic: map['is_public'] as bool? ?? true,
      memberCount: map['member_count'] as int? ?? 0,
    );
  }

  // Convert to database Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'created_by': createdBy,
      'created_at': createdAt.toIso8601String(),
      'is_default': isDefault,
      'is_public': isPublic,
      if (iconUrl != null) 'icon_url': iconUrl,
    };
  }
}
