import 'user.dart';

class MonthlyDraw {
  final String id;
  final String groupId;
  final int month;
  final int year;
  final DateTime drawDate;
  final List<Map<String, dynamic>> eligibleMembers;
  final String? winnerId;
  final double prizeAmount;
  final String serverSeed;
  final String serverSeedHash;
  final String clientSeed;
  final int nonce;
  final String resultHash;
  final String status;
  final String? notes;
  final DateTime createdAt;
  final DateTime updatedAt;
  final User? winner;

  MonthlyDraw({
    required this.id,
    required this.groupId,
    required this.month,
    required this.year,
    required this.drawDate,
    required this.eligibleMembers,
    this.winnerId,
    required this.prizeAmount,
    required this.serverSeed,
    required this.serverSeedHash,
    required this.clientSeed,
    required this.nonce,
    required this.resultHash,
    required this.status,
    this.notes,
    required this.createdAt,
    required this.updatedAt,
    this.winner,
  });

  factory MonthlyDraw.fromJson(Map<String, dynamic> json) {
    return MonthlyDraw(
      id: json['id'],
      groupId: json['group_id'],
      month: _parseInt(json['month']),
      year: _parseInt(json['year']),
      drawDate: DateTime.parse(json['draw_date']),
      eligibleMembers: _parseEligibleMembers(json['eligible_members']),
      winnerId: json['winner_id'],
      prizeAmount: _parseDouble(json['prize_amount']),
      serverSeed: json['server_seed'] ?? '',
      serverSeedHash: json['server_seed_hash'] ?? '',
      clientSeed: json['client_seed'] ?? '',
      nonce: _parseInt(json['nonce']),
      resultHash: json['result_hash'] ?? '',
      status: json['status'],
      notes: json['notes'],
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: DateTime.parse(json['updated_at']),
      winner: json['winner'] != null ? User.fromJson(json['winner']) : 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) {
      try {
        return double.parse(value);
      } catch (e) {
        print('Error parsing string to double: $value, error: $e');
        return 0.0;
      }
    }
    if (value is num) return value.toDouble();
    print('Warning: Cannot parse $value (${value.runtimeType}) to double, returning 0.0');
    return 0.0;
  }

  static int _parseInt(dynamic value) {
    if (value == null) return 0;
    if (value is int) return value;
    if (value is String) {
      try {
        return int.parse(value);
      } catch (e) {
        print('Error parsing string to int: $value, error: $e');
        return 0;
      }
    }
    if (value is double) return value.toInt();
    if (value is num) return value.toInt();
    print('Warning: Cannot parse $value (${value.runtimeType}) to int, returning 0');
    return 0;
  }

  static List<Map<String, dynamic>> _parseEligibleMembers(dynamic value) {
    if (value == null) return [];
    if (value is List) {
      return value.map((item) {
        if (item is Map<String, dynamic>) {
          return item;
        } else if (item is Map) {
          return Map<String, dynamic>.from(item);
        } else {
          return <String, dynamic>{};
        }
      }).toList();
    }
    return [];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'group_id': groupId,
      'month': month,
      'year': year,
      'draw_date': drawDate.toIso8601String(),
      'eligible_members': eligibleMembers,
      'winner_id': winnerId,
      'prize_amount': prizeAmount,
      'server_seed': serverSeed,
      'server_seed_hash': serverSeedHash,
      'client_seed': clientSeed,
      'nonce': nonce,
      'result_hash': resultHash,
      'status': status,
      'notes': notes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'winner': winner?.toJson(),
    };
  }

  // Helper methods
  bool get isPending => status == 'pending';
  bool get isCompleted => status == 'completed';
  bool get isCancelled => status == 'cancelled';
  
  String get monthYear => '$month/$year';
}
