import 'package:p_tits_pas/models/dossier_unifie.dart';
import 'package:p_tits_pas/utils/reprise_mapper.dart';

/// Réponse GET /auth/reprise-dossier. Tickets #111, #112.
class RepriseDossier {
  final String id;
  final String email;
  final String? prenom;
  final String? nom;
  final String? telephone;
  final String? adresse;
  final String? ville;
  final String? codePostal;
  final String? numeroDossier;
  final String role;
  final String? photoUrl;
  final String? genre;
  final String? situationFamiliale;

  final List<ParentDossier> parents;
  final List<EnfantDossier> enfants;
  final String? texteMotivation;

  final bool consentementPhoto;
  final String? dateNaissance;
  final String? lieuNaissanceVille;
  final String? lieuNaissancePays;
  final String? numeroAgrement;
  final String? nir;
  final String? dateAgrement;
  final int? nbMaxEnfants;
  final int? placeDisponible;
  final String? biographie;

  const RepriseDossier({
    required this.id,
    required this.email,
    this.prenom,
    this.nom,
    this.telephone,
    this.adresse,
    this.ville,
    this.codePostal,
    this.numeroDossier,
    required this.role,
    this.photoUrl,
    this.genre,
    this.situationFamiliale,
    this.parents = const [],
    this.enfants = const [],
    this.texteMotivation,
    this.consentementPhoto = false,
    this.dateNaissance,
    this.lieuNaissanceVille,
    this.lieuNaissancePays,
    this.numeroAgrement,
    this.nir,
    this.dateAgrement,
    this.nbMaxEnfants,
    this.placeDisponible,
    this.biographie,
  });

  bool get isParent => role == 'parent';
  bool get isAm => role == 'assistante_maternelle';

  static Map<String, dynamic>? _nestedMap(dynamic value) {
    if (value is Map) return Map<String, dynamic>.from(value);
    return null;
  }

  static dynamic _firstNonNull(List<dynamic> values) {
    for (final v in values) {
      if (v != null) return v;
    }
    return null;
  }

  factory RepriseDossier.fromJson(Map<String, dynamic> json) {
    final nestedUser = _nestedMap(json['user']);
    final nestedDossier = _nestedMap(json['dossier']);

    final parentsRaw = json['parents'];
    final parentsList = parentsRaw is List
        ? parentsRaw
            .where((e) => e is Map)
            .map((e) => ParentDossier.fromJson(Map<String, dynamic>.from(e as Map)))
            .toList()
        : <ParentDossier>[];

    final enfantsRaw = json['enfants'];
    final enfantsList = enfantsRaw is List
        ? enfantsRaw
            .where((e) => e is Map)
            .map((e) => EnfantDossier.fromJson(Map<String, dynamic>.from(e as Map)))
            .toList()
        : <EnfantDossier>[];

    return RepriseDossier(
      id: json['id']?.toString() ?? '',
      email: json['email']?.toString() ?? '',
      prenom: json['prenom']?.toString(),
      nom: json['nom']?.toString(),
      telephone: json['telephone']?.toString(),
      adresse: json['adresse']?.toString(),
      ville: json['ville']?.toString(),
      codePostal: json['code_postal']?.toString(),
      numeroDossier: json['numero_dossier']?.toString(),
      role: json['role']?.toString() ?? '',
      photoUrl: json['photo_url']?.toString(),
      genre: json['genre']?.toString(),
      situationFamiliale: json['situation_familiale']?.toString(),
      parents: parentsList,
      enfants: enfantsList,
      texteMotivation: (json['texte_motivation'] ?? json['presentation_dossier'])
          ?.toString(),
      consentementPhoto: RepriseMapper.optionalBool(json['consentement_photo']) ||
          RepriseMapper.optionalBool(json['consent_photo']) ||
          RepriseMapper.optionalBool(nestedUser?['consentement_photo']),
      dateNaissance: RepriseMapper.optionalDateString(
        _firstNonNull([
          json['date_naissance'],
          json['dateNaissance'],
          nestedUser?['date_naissance'],
          nestedUser?['dateNaissance'],
        ]),
      ),
      lieuNaissanceVille: _firstNonNull([
        json['lieu_naissance_ville'],
        json['lieuNaissanceVille'],
        nestedUser?['lieu_naissance_ville'],
        nestedUser?['lieuNaissanceVille'],
      ])?.toString(),
      lieuNaissancePays: _firstNonNull([
        json['lieu_naissance_pays'],
        json['lieuNaissancePays'],
        nestedUser?['lieu_naissance_pays'],
        nestedUser?['lieuNaissancePays'],
      ])?.toString(),
      numeroAgrement: _firstNonNull([
        json['numero_agrement'],
        json['numero_agrement_am'],
        json['numeroAgrement'],
        nestedDossier?['numero_agrement'],
        nestedDossier?['numeroAgrement'],
      ])?.toString(),
      nir: _firstNonNull([
        json['nir'],
        nestedDossier?['nir'],
      ])?.toString(),
      dateAgrement: RepriseMapper.optionalDateString(
        _firstNonNull([
          json['date_agrement'],
          json['dateAgrement'],
          nestedDossier?['date_agrement'],
          nestedDossier?['dateAgrement'],
        ]),
      ),
      nbMaxEnfants: RepriseMapper.optionalInt(
        _firstNonNull([
          json['nb_max_enfants'],
          json['capacite_accueil'],
          json['nbMaxEnfants'],
          nestedDossier?['nb_max_enfants'],
          nestedDossier?['capacite_accueil'],
        ]),
      ),
      placeDisponible: RepriseMapper.optionalInt(
        _firstNonNull([
          json['place_disponible'],
          json['places_disponibles'],
          json['placesDisponibles'],
          nestedDossier?['place_disponible'],
          nestedDossier?['places_disponibles'],
        ]),
      ),
      biographie: (json['biographie'] ?? json['presentation'])?.toString(),
    );
  }
}
