import Foundation
import SwiftUI
import ComposeApp

// MARK: - Complete Task Form State

/// Form state container for completing a task
struct CompleteTaskFormState: FormState {
    var completedByName = FormField<String>()
    var actualCost = FormField<String>()
    var notes = FormField<String>()
    var rating: Int = 3
    var completionDate: Date = Date()
    var selectedImages: [UIImage] = []

    var isValid: Bool {
        completedByName.isValid
    }

    mutating func validateAll() {
        completedByName.validate { value in
            ValidationRules.validateRequired(value, fieldName: "Completed By")
        }
    }

    mutating func reset() {
        completedByName = FormField<String>()
        actualCost = FormField<String>()
        notes = FormField<String>()
        rating = 3
        completionDate = Date()
        selectedImages = []
    }

    /// Convert actualCost string to optional Double
    var actualCostValue: Double? {
        actualCost.value.asOptionalDouble
    }
}

// MARK: - Task Form State

/// Form state container for creating/editing a task
struct TaskFormState: FormState {
    var title = FormField<String>()
    var description = FormField<String>()
    var selectedResidenceId: Int32?
    var selectedCategoryId: Int32?
    var selectedFrequencyId: Int32?
    var selectedPriorityId: Int32?
    var selectedStatusId: Int32?
    var dueDate: Date = Date()
    var intervalDays = FormField<String>()
    var estimatedCost = FormField<String>()

    // For edit mode
    var existingTaskId: Int32?

    var isEditMode: Bool {
        existingTaskId != nil
    }

    var isValid: Bool {
        !title.isEmpty &&
        selectedCategoryId != nil &&
        selectedFrequencyId != nil &&
        selectedPriorityId != nil &&
        selectedStatusId != nil &&
        (isEditMode || selectedResidenceId != nil)
    }

    mutating func validateAll() {
        title.validate { value in
            ValidationRules.validateRequired(value, fieldName: "Title")
        }
    }

    mutating func reset() {
        title = FormField<String>()
        description = FormField<String>()
        selectedResidenceId = nil
        selectedCategoryId = nil
        selectedFrequencyId = nil
        selectedPriorityId = nil
        selectedStatusId = nil
        dueDate = Date()
        intervalDays = FormField<String>()
        estimatedCost = FormField<String>()
        existingTaskId = nil
    }

    /// Convert estimatedCost string to optional Double
    var estimatedCostValue: Double? {
        estimatedCost.value.asOptionalDouble
    }

    /// Convert intervalDays string to optional Int
    var intervalDaysValue: Int? {
        intervalDays.value.asOptionalInt
    }
}
