import SwiftUI
import SwiftData

/// A single contact field stored with the business card
/// Supports ordering and multiple fields of the same type
@Model
final class ContactField {
    /// Unique identifier
    var id: UUID = UUID()
    
    /// The type ID (matches ContactFieldType.id)
    var typeId: String = ""
    
    /// The value (email address, phone number, URL, etc.)
    var value: String = ""
    
    /// Optional title/label (e.g., "Work", "Personal", "Connect with me")
    var title: String = ""
    
    /// Order index for drag-to-reorder support
    var orderIndex: Int = 0
    
    /// Parent business card (inverse relationship)
    var card: BusinessCard?
    
    /// Parent contact (inverse relationship for contact fields)
    var contact: Contact?
    
    init(typeId: String, value: String = "", title: String = "", orderIndex: Int = 0) {
        self.id = UUID()
        self.typeId = typeId
        self.value = value
        self.title = title
        self.orderIndex = orderIndex
    }
    
    /// Convenience initializer from ContactFieldType
    convenience init(fieldType: ContactFieldType, value: String = "", title: String = "", orderIndex: Int = 0) {
        self.init(typeId: fieldType.id, value: value, title: title, orderIndex: orderIndex)
    }
    
    /// Gets the ContactFieldType for this field
    @MainActor
    var fieldType: ContactFieldType? {
        ContactFieldType.allCases.first { $0.id == typeId }
    }
    
    /// Display name from the field type
    @MainActor
    var displayName: String {
        fieldType?.displayName ?? typeId
    }
    
    /// Formatted display value using the field type's formatter
    /// For addresses, this returns a multi-line formatted string
    /// For other fields, returns the value as-is
    @MainActor
    var displayValue: String {
        fieldType?.formattedDisplayValue(value) ?? value
    }
    
    /// Returns an Image view for this field's icon
    @MainActor
    func iconImage() -> Image {
        fieldType?.iconImage() ?? Image(systemName: "link")
    }
    
    /// Icon color from the field type
    @MainActor
    var iconColor: Color {
        fieldType?.iconColor ?? Color.gray
    }
    
    /// Whether this is a custom symbol (for rendering)
    @MainActor
    var isCustomSymbol: Bool {
        fieldType?.isCustomSymbol ?? false
    }
    
    /// System image name for legacy compatibility
    @MainActor
    var systemImage: String {
        fieldType?.systemImage ?? "link"
    }
    
    /// Builds the URL for this field
    @MainActor
    func buildURL() -> URL? {
        fieldType?.buildURL(value: value)
    }
    
    // MARK: - Postal Address Support
    
    /// Returns the postal address if this is an address field
    /// Attempts to parse as JSON first, falls back to legacy string parsing
    @MainActor
    var postalAddress: PostalAddress? {
        guard typeId == "address" else { return nil }
        
        // Parse as structured PostalAddress
        if let address = PostalAddress.decode(from: value), address.hasValue {
            return address
        }
        
        return nil
    }
    
    /// Sets the postal address (stores as JSON)
    @MainActor
    func setPostalAddress(_ address: PostalAddress) {
        self.value = address.encode()
    }
}

// MARK: - Conversion helpers

extension ContactField {
    /// Creates an AddedContactField for use in the editor UI
    @MainActor
    func toAddedContactField() -> AddedContactField? {
        guard let type = fieldType else { return nil }
        return AddedContactField(id: id, fieldType: type, value: value, title: title)
    }
    
    /// Updates from an AddedContactField
    func update(from addedField: AddedContactField) {
        self.value = addedField.value
        self.title = addedField.title
    }
}
