import 'package:tugas_akhir_supabase/domain/entities/field.dart';
import 'package:tugas_akhir_supabase/data/models/field_model.dart';

/// Utility class to help with field model conversions
class FieldConverter {
  /// Convert from JSON to Field entity
  static Field fromJson(Map<String, dynamic> json) {
    DateTime createdAt;
    DateTime updatedAt;

    try {
      createdAt =
          json['created_at'] != null
              ? json['created_at'] is DateTime
                  ? json['created_at']
                  : DateTime.parse(json['created_at'].toString())
              : DateTime.now();
    } catch (e) {
      print('Error parsing created_at: $e');
      createdAt = DateTime.now();
    }

    try {
      updatedAt =
          json['updated_at'] != null
              ? json['updated_at'] is DateTime
                  ? json['updated_at']
                  : DateTime.parse(json['updated_at'].toString())
              : DateTime.now();
    } catch (e) {
      print('Error parsing updated_at: $e');
      updatedAt = DateTime.now();
    }

    return Field(
      id: json['id'].toString(),
      name: json['name']?.toString() ?? 'Lahan Tanpa Nama',
      userId: json['user_id'].toString(),
      plotCount:
          json['plot_count'] is int
              ? json['plot_count']
              : int.tryParse(json['plot_count']?.toString() ?? '1') ?? 1,
      region: json['region']?.toString(),
      location: json['location']?.toString(),
      latitude:
          json['latitude'] is double
              ? json['latitude']
              : double.tryParse(json['latitude']?.toString() ?? '0'),
      longitude:
          json['longitude'] is double
              ? json['longitude']
              : double.tryParse(json['longitude']?.toString() ?? '0'),
      areaSize:
          json['area_size'] is double
              ? json['area_size']
              : double.tryParse(json['area_size']?.toString() ?? '0'),
      areaUnit: json['area_unit']?.toString() ?? 'm²',
      ownershipType: json['ownership_type']?.toString() ?? 'Milik Sendiri',
      ownerName: json['owner_name']?.toString(),
      regionSpecificData:
          json['region_specific_data'] is Map
              ? Map<String, dynamic>.from(json['region_specific_data'])
              : null,
      createdAt: createdAt,
      updatedAt: updatedAt,
    );
  }

  /// Convert from Field entity to JSON
  static Map<String, dynamic> toJson(Field field) {
    final Map<String, dynamic> json = {
      'id': field.id,
      'name': field.name,
      'plot_count': field.plotCount,
      'user_id': field.userId,
      'region': field.region,
      'location': field.location,
      'latitude': field.latitude,
      'longitude': field.longitude,
      'area_size': field.areaSize,
      'area_unit': field.areaUnit,
      'ownership_type': field.ownershipType,
      'region_specific_data': field.regionSpecificData,
    };

    // Only add owner_name if it's not null or empty
    if (field.ownerName != null && field.ownerName!.isNotEmpty) {
      json['owner_name'] = field.ownerName;
    }

    return json;
  }

  /// Create a copy of a Field with updated properties
  static Field copyWith({
    required Field field,
    String? name,
    String? region,
    String? location,
    double? latitude,
    double? longitude,
    double? areaSize,
    String? areaUnit,
    int? plotCount,
    String? ownershipType,
    String? ownerName,
    Map<String, dynamic>? regionSpecificData,
  }) {
    return Field(
      id: field.id,
      name: name ?? field.name,
      region: region ?? field.region,
      location: location ?? field.location,
      latitude: latitude ?? field.latitude,
      longitude: longitude ?? field.longitude,
      areaSize: areaSize ?? field.areaSize,
      areaUnit: areaUnit ?? field.areaUnit,
      plotCount: plotCount ?? field.plotCount,
      ownershipType: ownershipType ?? field.ownershipType,
      ownerName: ownerName ?? field.ownerName,
      regionSpecificData: regionSpecificData ?? field.regionSpecificData,
      userId: field.userId,
      createdAt: field.createdAt,
      updatedAt: DateTime.now(),
    );
  }
}
