import 'user.dart';

class GroupMember {
  final String id;
  final String groupId;
  final String userId;
  final DateTime joinedDate;
  final String status;
  final double totalPaid;
  final double totalWon;
  final DateTime createdAt;
  final DateTime updatedAt;
  final User? user;

  GroupMember({
    required this.id,
    required this.groupId,
    required this.userId,
    required this.joinedDate,
    required this.status,
    required this.totalPaid,
    required this.totalWon,
    required this.createdAt,
    required this.updatedAt,
    this.user,
  });

  factory GroupMember.fromJson(Map<String, dynamic> json) {
    return GroupMember(
      id: json['id'] ?? '',
      groupId: json['group_id'] ?? '',
      userId: json['user_id'] ?? '',
      joinedDate: json['joined_date'] != null ? DateTime.parse(json['joined_date']) : DateTime.now(),
      status: json['status'] ?? 'active',
      totalPaid: _parseDouble(json['total_paid']),
      totalWon: _parseDouble(json['total_won']),
      createdAt: json['created_at'] != null ? DateTime.parse(json['created_at']) : DateTime.now(),
      updatedAt: json['updated_at'] != null ? DateTime.parse(json['updated_at']) : DateTime.now(),
      user: json['User'] != null ? User.fromJson(json['User']) : null,
    );
  }

  static double _parseDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) return double.parse(value);
    throw ArgumentError('Cannot parse $value to double');
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'group_id': groupId,
      'user_id': userId,
      'joined_date': joinedDate.toIso8601String(),
      'status': status,
      'total_paid': totalPaid,
      'total_won': totalWon,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'User': user?.toJson(),
    };
  }

  // Helper methods
  bool get isActive => status == 'active';
  bool get isInactive => status == 'inactive';
  bool get isRemoved => status == 'removed';
}
