import 'package:p_tits_pas/models/parent_child_summary.dart';
import 'package:p_tits_pas/models/user.dart';

class ParentModel {
  final AppUser user;
  final AppUser? coParent;
  final int childrenCount;
  final List<ParentChildSummary> children;

  ParentModel({
    required this.user,
    this.coParent,
    this.childrenCount = 0,
    this.children = const [],
  });

  factory ParentModel.fromJson(Map<String, dynamic> json) {
    final root = Map<String, dynamic>.from(json);
    final userJson = Map<String, dynamic>.from(root['user'] ?? root);
    if (root['numero_dossier'] != null && userJson['numero_dossier'] == null) {
      userJson['numero_dossier'] = root['numero_dossier'];
    }
    final user = AppUser.fromJson(userJson);

    AppUser? coParent;
    final coParentRaw = root['co_parent'];
    if (coParentRaw is Map) {
      coParent = AppUser.fromJson(Map<String, dynamic>.from(coParentRaw));
    }

    final children = _parseChildren(root);
    final links = root['parentChildren'] ?? root['parent_children'];
    final linkCount = links is List ? links.length : 0;

    return ParentModel(
      user: user,
      coParent: coParent,
      childrenCount: children.isNotEmpty ? children.length : linkCount,
      children: children,
    );
  }

  static List<ParentChildSummary> _parseChildren(Map<String, dynamic> json) {
    final children = <ParentChildSummary>[];
    final seen = <String>{};

    void add(ParentChildSummary? child) {
      if (child == null || child.id.isEmpty || seen.contains(child.id)) return;
      seen.add(child.id);
      children.add(child);
    }

    final links = json['parentChildren'] ?? json['parent_children'];
    if (links is List) {
      for (final link in links) {
        if (link is! Map) continue;
        add(ParentChildSummary.fromParentChildLink(
          Map<String, dynamic>.from(link),
        ));
      }
    }

    return children;
  }

  /// Nombre d’enfants distincts du foyer (ce parent + co-parent / même dossier).
  /// Évite Claire=7 / Thomas=6 quand un lien n’est que sur un des deux (#157).
  static int foyerChildrenCount(
    ParentModel parent,
    List<ParentModel> allParents,
  ) {
    final memberIds = <String>{parent.user.id};
    final coId = parent.coParent?.id.trim();
    if (coId != null && coId.isNotEmpty) memberIds.add(coId);

    final dossier = (parent.user.numeroDossier ?? '').trim();

    for (final other in allParents) {
      if (memberIds.contains(other.user.id)) continue;
      final otherCo = other.coParent?.id.trim();
      if (otherCo != null && memberIds.contains(otherCo)) {
        memberIds.add(other.user.id);
        continue;
      }
      if (dossier.isNotEmpty &&
          (other.user.numeroDossier ?? '').trim() == dossier) {
        memberIds.add(other.user.id);
        final oc = other.coParent?.id.trim();
        if (oc != null && oc.isNotEmpty) memberIds.add(oc);
      }
    }

    final childIds = <String>{};
    for (final p in allParents) {
      if (!memberIds.contains(p.user.id)) continue;
      for (final c in p.children) {
        final id = c.id.trim();
        if (id.isNotEmpty) childIds.add(id);
      }
      // Repli si la liste enfants n’est pas hydratée.
      if (p.children.isEmpty && p.childrenCount > 0) {
        // Impossible de dédupliquer sans IDs : on prend au moins ce compte.
        // (évite d’afficher 0 si l’API n’envoie que childrenCount)
      }
    }

    if (childIds.isNotEmpty) return childIds.length;

    var maxCount = 0;
    for (final p in allParents) {
      if (!memberIds.contains(p.user.id)) continue;
      final n = p.children.isNotEmpty ? p.children.length : p.childrenCount;
      if (n > maxCount) maxCount = n;
    }
    return maxCount;
  }
}
