import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';

part 'passage_model.g.dart';

@HiveType(typeId: 4)
class PassageModel extends HiveObject {
  @HiveField(0)
  final int id;

  @HiveField(1)
  final int fkOperation;

  @HiveField(2)
  final int? fkSector;

  @HiveField(3)
  final int fkUser;

  @HiveField(4)
  final int fkType;

  @HiveField(5)
  final String fkAdresse;

  @HiveField(6)
  final DateTime? passedAt;

  @HiveField(7)
  final String numero;

  @HiveField(8)
  final String rue;

  @HiveField(9)
  final String rueBis;

  @HiveField(10)
  final String ville;

  @HiveField(11)
  final String residence;

  @HiveField(12)
  final int fkHabitat;

  @HiveField(13)
  final String appt;

  @HiveField(14)
  final String niveau;

  @HiveField(15)
  final String gpsLat;

  @HiveField(16)
  final String gpsLng;

  @HiveField(17)
  final String nomRecu;

  @HiveField(18)
  final String remarque;

  @HiveField(19)
  final String montant;

  @HiveField(20)
  final int fkTypeReglement;

  @HiveField(21)
  final String emailErreur;

  @HiveField(22)
  final int nbPassages;

  @HiveField(23)
  final String name;

  @HiveField(24)
  final String email;

  @HiveField(25)
  final String phone;

  @HiveField(26)
  DateTime lastSyncedAt;

  @HiveField(27)
  bool isActive;

  @HiveField(28)
  bool isSynced;

  @HiveField(29)
  String? stripePaymentId;

  @HiveField(30)
  String? stripePaymentLinkId;

  @HiveField(31)
  String? stripePaymentLinkUrl;

  PassageModel({
    required this.id,
    required this.fkOperation,
    this.fkSector,
    required this.fkUser,
    required this.fkType,
    required this.fkAdresse,
    this.passedAt,
    required this.numero,
    required this.rue,
    this.rueBis = '',
    required this.ville,
    this.residence = '',
    required this.fkHabitat,
    this.appt = '',
    this.niveau = '',
    required this.gpsLat,
    required this.gpsLng,
    this.nomRecu = '',
    this.remarque = '',
    required this.montant,
    required this.fkTypeReglement,
    this.emailErreur = '',
    required this.nbPassages,
    required this.name,
    this.email = '',
    this.phone = '',
    required this.lastSyncedAt,
    this.isActive = true,
    this.isSynced = false,
    this.stripePaymentId,
    this.stripePaymentLinkId,
    this.stripePaymentLinkUrl,
  });

  // Factory pour convertir depuis JSON (API)
  factory PassageModel.fromJson(Map<String, dynamic> json) {
    try {
      // Convertir l'ID en int, qu'il soit déjà int ou string
      final dynamic rawId = json['id'];
      final int id = rawId is String ? int.parse(rawId) : rawId as int;

      // Convertir les autres champs numériques
      final dynamic rawFkOperation = json['fk_operation'];
      final int fkOperation = rawFkOperation is String ? int.parse(rawFkOperation) : rawFkOperation as int;

      final dynamic rawFkSector = json['fk_sector'];
      final int? fkSector = rawFkSector == null 
          ? null 
          : rawFkSector is String 
              ? int.parse(rawFkSector) 
              : rawFkSector as int;

      final dynamic rawFkUser = json['fk_user'];
      final int fkUser = rawFkUser is String ? int.parse(rawFkUser) : rawFkUser as int;

      final dynamic rawFkType = json['fk_type'];
      final int fkType = rawFkType is String ? int.parse(rawFkType) : rawFkType as int;

      final dynamic rawFkHabitat = json['fk_habitat'];
      final int fkHabitat = rawFkHabitat is String ? int.parse(rawFkHabitat) : rawFkHabitat as int;

      final dynamic rawFkTypeReglement = json['fk_type_reglement'];
      final int fkTypeReglement = rawFkTypeReglement is String ? int.parse(rawFkTypeReglement) : rawFkTypeReglement as int;

      final dynamic rawNbPassages = json['nb_passages'];
      final int nbPassages = rawNbPassages is String ? int.parse(rawNbPassages) : rawNbPassages as int;

      // Convertir la date (nullable)
      final DateTime? passedAt = json['passed_at'] != null 
          ? DateTime.parse(json['passed_at']) 
          : null;

      return PassageModel(
        id: id,
        fkOperation: fkOperation,
        fkSector: fkSector,
        fkUser: fkUser,
        fkType: fkType,
        fkAdresse: json['fk_adresse']?.toString() ?? '', // ← Gestion null
        passedAt: passedAt,
        numero: json['numero']?.toString() ?? '', // ← Gestion null
        rue: json['rue']?.toString() ?? '', // ← Gestion null
        rueBis: json['rue_bis']?.toString() ?? '',
        ville: json['ville']?.toString() ?? '', // ← Gestion null
        residence: json['residence']?.toString() ?? '',
        fkHabitat: fkHabitat,
        appt: json['appt']?.toString() ?? '',
        niveau: json['niveau']?.toString() ?? '',
        gpsLat: json['gps_lat']?.toString() ?? '', // ← Gestion null
        gpsLng: json['gps_lng']?.toString() ?? '', // ← Gestion null
        nomRecu: json['nom_recu']?.toString() ?? '', // ← Gestion null explicite
        remarque: json['remarque']?.toString() ?? '',
        montant: json['montant']?.toString() ?? '0.00', // ← Gestion null avec fallback
        fkTypeReglement: fkTypeReglement,
        emailErreur: json['email_erreur']?.toString() ?? '',
        nbPassages: nbPassages,
        name: json['name']?.toString() ?? '', // ← Gestion null
        email: json['email']?.toString() ?? '',
        phone: json['phone']?.toString() ?? '',
        lastSyncedAt: DateTime.now(),
        isActive: true,
        isSynced: true,
        stripePaymentId: json['stripe_payment_id']?.toString(),
        stripePaymentLinkId: json['stripe_payment_link_id']?.toString(),
        stripePaymentLinkUrl: json['stripe_payment_link_url']?.toString(),
      );
    } catch (e) {
      debugPrint('❌ Erreur parsing PassageModel: $e');
      debugPrint('❌ Données JSON: $json');
      rethrow;
    }
  }

  // Convertir en JSON pour l'API
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'fk_operation': fkOperation,
      'fk_sector': fkSector,
      'fk_user': fkUser,
      'fk_type': fkType,
      'fk_adresse': fkAdresse,
      'passed_at': passedAt?.toIso8601String(),
      'numero': numero,
      'rue': rue,
      'rue_bis': rueBis,
      'ville': ville,
      'residence': residence,
      'fk_habitat': fkHabitat,
      'appt': appt,
      'niveau': niveau,
      'gps_lat': gpsLat,
      'gps_lng': gpsLng,
      'nom_recu': nomRecu,
      'remarque': remarque,
      'montant': montant,
      'fk_type_reglement': fkTypeReglement,
      'email_erreur': emailErreur,
      'nb_passages': nbPassages,
      'name': name,
      'email': email,
      'phone': phone,
      'stripe_payment_id': stripePaymentId,
      'stripe_payment_link_id': stripePaymentLinkId,
      'stripe_payment_link_url': stripePaymentLinkUrl,
    };
  }

  // Copier avec de nouvelles valeurs
  PassageModel copyWith({
    int? id,
    int? fkOperation,
    int? fkSector,
    int? fkUser,
    int? fkType,
    String? fkAdresse,
    DateTime? passedAt,
    String? numero,
    String? rue,
    String? rueBis,
    String? ville,
    String? residence,
    int? fkHabitat,
    String? appt,
    String? niveau,
    String? gpsLat,
    String? gpsLng,
    String? nomRecu,
    String? remarque,
    String? montant,
    int? fkTypeReglement,
    String? emailErreur,
    int? nbPassages,
    String? name,
    String? email,
    String? phone,
    DateTime? lastSyncedAt,
    bool? isActive,
    bool? isSynced,
    String? stripePaymentId,
    String? stripePaymentLinkId,
    String? stripePaymentLinkUrl,
  }) {
    return PassageModel(
      id: id ?? this.id,
      fkOperation: fkOperation ?? this.fkOperation,
      fkSector: fkSector ?? this.fkSector,
      fkUser: fkUser ?? this.fkUser,
      fkType: fkType ?? this.fkType,
      fkAdresse: fkAdresse ?? this.fkAdresse,
      passedAt: passedAt ?? this.passedAt,
      numero: numero ?? this.numero,
      rue: rue ?? this.rue,
      rueBis: rueBis ?? this.rueBis,
      ville: ville ?? this.ville,
      residence: residence ?? this.residence,
      fkHabitat: fkHabitat ?? this.fkHabitat,
      appt: appt ?? this.appt,
      niveau: niveau ?? this.niveau,
      gpsLat: gpsLat ?? this.gpsLat,
      gpsLng: gpsLng ?? this.gpsLng,
      nomRecu: nomRecu ?? this.nomRecu,
      remarque: remarque ?? this.remarque,
      montant: montant ?? this.montant,
      fkTypeReglement: fkTypeReglement ?? this.fkTypeReglement,
      emailErreur: emailErreur ?? this.emailErreur,
      nbPassages: nbPassages ?? this.nbPassages,
      name: name ?? this.name,
      email: email ?? this.email,
      phone: phone ?? this.phone,
      lastSyncedAt: lastSyncedAt ?? this.lastSyncedAt,
      isActive: isActive ?? this.isActive,
      isSynced: isSynced ?? this.isSynced,
      stripePaymentId: stripePaymentId ?? this.stripePaymentId,
      stripePaymentLinkId: stripePaymentLinkId ?? this.stripePaymentLinkId,
      stripePaymentLinkUrl: stripePaymentLinkUrl ?? this.stripePaymentLinkUrl,
    );
  }

  @override
  String toString() {
    return 'PassageModel(id: $id, fkOperation: $fkOperation, fkSector: $fkSector, fkUser: $fkUser, fkType: $fkType, adresse: $fkAdresse, ville: $ville, montant: $montant, passedAt: $passedAt)';
  }
}
