import 'user.dart';
import 'group_member.dart';
import 'monthly_draw.dart';

class ChitGroup {
  final String id;
  final String name;
  final double totalValue;
  final double monthlyInstallment;
  final int durationMonths;
  final int maxMembers;
  final double foremanCommissionAmount;
  final String? foremanCommissionType; // 'fixed' or 'percentage'
  final double? foremanCommissionRate; // percentage rate (0-100)
  final int drawDate;
  final String managerId;
  final String status;
  final DateTime? startDate;
  final DateTime? endDate;
  final DateTime createdAt;
  final DateTime updatedAt;
  final User? manager;
  final List<GroupMember>? members;
  final List<MonthlyDraw>? monthlyDraws;

  ChitGroup({
    required this.id,
    required this.name,
    required this.totalValue,
    required this.monthlyInstallment,
    required this.durationMonths,
    required this.maxMembers,
    required this.foremanCommissionAmount,
    this.foremanCommissionType,
    this.foremanCommissionRate,
    required this.drawDate,
    required this.managerId,
    required this.status,
    this.startDate,
    this.endDate,
    required this.createdAt,
    required this.updatedAt,
    this.manager,
    this.members,
    this.monthlyDraws,
  });

  factory ChitGroup.fromJson(Map<String, dynamic> json) {
    return ChitGroup(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      totalValue: _parseDouble(json['total_value']),
      monthlyInstallment: _parseDouble(json['monthly_installment']),
      durationMonths: json['duration_months'] is int ? json['duration_months'] : int.parse(json['duration_months']?.toString() ?? '0'),
      maxMembers: json['max_members'] is int ? json['max_members'] : int.parse(json['max_members']?.toString() ?? '0'),
      foremanCommissionAmount: _parseDouble(json['foreman_commission_amount']),
      foremanCommissionType: json['foreman_commission_type'],
      foremanCommissionRate: json['foreman_commission_rate'] != null ? _parseDouble(json['foreman_commission_rate']) : null,
      drawDate: json['draw_date'] is int ? json['draw_date'] : int.parse(json['draw_date']?.toString() ?? '15'),
      managerId: json['manager_id'] ?? '',
      status: json['status'] ?? 'forming',
      startDate: json['start_date'] != null ? DateTime.parse(json['start_date']) : null,
      endDate: json['end_date'] != null ? DateTime.parse(json['end_date']) : null,
      createdAt: json['created_at'] != null ? DateTime.parse(json['created_at']) : DateTime.now(),
      updatedAt: json['updated_at'] != null ? DateTime.parse(json['updated_at']) : DateTime.now(),
      manager: json['manager'] != null ? User.fromJson(json['manager']) : null,
      members: json['members'] != null 
          ? (json['members'] as List).map((m) => GroupMember.fromJson(m)).toList()
          : null,
      monthlyDraws: json['monthly_draws'] != null 
          ? (json['monthly_draws'] as List).map((d) => MonthlyDraw.fromJson(d)).toList()
          : 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,
      'name': name,
      'total_value': totalValue,
      'monthly_installment': monthlyInstallment,
      'duration_months': durationMonths,
      'max_members': maxMembers,
      'foreman_commission_amount': foremanCommissionAmount,
      'foreman_commission_type': foremanCommissionType,
      'foreman_commission_rate': foremanCommissionRate,
      'draw_date': drawDate,
      'manager_id': managerId,
      'status': status,
      'start_date': startDate?.toIso8601String(),
      'end_date': endDate?.toIso8601String(),
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'manager': manager?.toJson(),
      'members': members?.map((m) => m.toJson()).toList(),
      'monthly_draws': monthlyDraws?.map((d) => d.toJson()).toList(),
    };
  }

  // Helper methods
  bool get isForming => status == 'forming';
  bool get isActive => status == 'active';
  bool get isCompleted => status == 'completed';
  
  int get currentMemberCount => members?.length ?? 0;
  bool get isFull => currentMemberCount >= maxMembers;
  bool get canStart => currentMemberCount >= 2 && isForming;
  
  double get totalPrizePool {
    final totalCollection = currentMemberCount * monthlyInstallment;
    return totalCollection - foremanCommissionAmount;
  }
}
