import 'package:p_tits_pas/models/enfant_admin_model.dart';
import 'package:p_tits_pas/utils/enfant_status_utils.dart';

/// Résumé enfant affiché dans la fiche parent (dashboard admin).
class ParentChildSummary {
  final String id;
  final String? firstName;
  final String? lastName;
  final String status;
  final String? photoUrl;
  final String? birthDate;
  final String? dueDate;

  ParentChildSummary({
    required this.id,
    this.firstName,
    this.lastName,
    required this.status,
    this.photoUrl,
    this.birthDate,
    this.dueDate,
  });

  String get fullName {
    final fn = (firstName ?? '').trim();
    final ln = (lastName ?? '').trim();
    if (fn.isEmpty && ln.isEmpty) return 'Enfant';
    if (ln.isEmpty) return fn;
    return '$fn $ln';
  }

  factory ParentChildSummary.fromJson(Map<String, dynamic> json) {
    return ParentChildSummary(
      id: (json['id'] ?? '').toString(),
      firstName: (json['first_name'] ?? json['prenom'])?.toString(),
      lastName: (json['last_name'] ?? json['nom'])?.toString(),
      status: normalizeEnfantStatus(
        (json['status'] ?? json['statut'])?.toString(),
      ),
      photoUrl: json['photo_url']?.toString(),
      birthDate: _dateString(json['birth_date']),
      dueDate: _dateString(json['due_date']),
    );
  }

  factory ParentChildSummary.fromEnfant(EnfantAdminModel enfant) {
    return ParentChildSummary(
      id: enfant.id,
      firstName: enfant.firstName,
      lastName: enfant.lastName,
      status: enfant.status,
      photoUrl: enfant.photoUrl,
      birthDate: enfant.birthDate,
      dueDate: enfant.dueDate,
    );
  }

  static String? _dateString(dynamic v) {
    if (v == null) return null;
    if (v is String) return v.split('T').first;
    return v.toString().split('T').first;
  }

  /// Parse un lien `parentChildren` (objet enfant imbriqué ou id seul).
  static ParentChildSummary? fromParentChildLink(Map<String, dynamic> link) {
    final childRaw = link['child'] ?? link['enfant'];
    if (childRaw is Map) {
      return ParentChildSummary.fromJson(Map<String, dynamic>.from(childRaw));
    }

    if (link.containsKey('first_name') ||
        link.containsKey('prenom') ||
        link.containsKey('id')) {
      final id = (link['id'] ?? '').toString();
      if (id.isNotEmpty &&
          (link.containsKey('first_name') || link.containsKey('prenom'))) {
        return ParentChildSummary.fromJson(link);
      }
    }

    final enfantId =
        link['enfantId'] ?? link['id_enfant'] ?? link['enfant_id'];
    if (enfantId != null && enfantId.toString().isNotEmpty) {
      return ParentChildSummary(
        id: enfantId.toString(),
        status: '',
      );
    }

    return null;
  }
}
