import Foundation
import SwiftUI
import ComposeApp

// MARK: - Residence Form State

/// Form state container for creating/editing a residence
struct ResidenceFormState: FormState {
    var name = FormField<String>()
    var address = FormField<String>()
    var city = FormField<String>()
    var state = FormField<String>()
    var zipCode = FormField<String>()
    var country = FormField<String>(initialValue: "USA")
    var selectedResidenceTypeId: Int32?
    var purchasePrice = FormField<String>()
    var purchaseDate: Date?
    var squareFootage = FormField<String>()
    var lotSize = FormField<String>()
    var yearBuilt = FormField<String>()
    var bedrooms = FormField<String>()
    var bathrooms = FormField<String>()
    var notes = FormField<String>()

    // For edit mode
    var existingResidenceId: Int32?

    var isEditMode: Bool {
        existingResidenceId != nil
    }

    var isValid: Bool {
        !name.isEmpty && selectedResidenceTypeId != nil
    }

    mutating func validateAll() {
        name.validate { ValidationRules.validateRequired($0, fieldName: "Name") }
    }

    mutating func reset() {
        name = FormField<String>()
        address = FormField<String>()
        city = FormField<String>()
        state = FormField<String>()
        zipCode = FormField<String>()
        country = FormField<String>(initialValue: "USA")
        selectedResidenceTypeId = nil
        purchasePrice = FormField<String>()
        purchaseDate = nil
        squareFootage = FormField<String>()
        lotSize = FormField<String>()
        yearBuilt = FormField<String>()
        bedrooms = FormField<String>()
        bathrooms = FormField<String>()
        notes = FormField<String>()
        existingResidenceId = nil
    }

    // MARK: - Computed Properties for API Calls

    var purchasePriceValue: Double? { purchasePrice.value.asOptionalDouble }
    var squareFootageValue: Int? { squareFootage.value.asOptionalInt }
    var lotSizeValue: Double? { lotSize.value.asOptionalDouble }
    var yearBuiltValue: Int? { yearBuilt.value.asOptionalInt }
    var bedroomsValue: Int? { bedrooms.value.asOptionalInt }
    var bathroomsValue: Double? { bathrooms.value.asOptionalDouble }
}
