import Foundation

@Observable
final class GoalsViewModel {
    private let api = FitnessAPI()

    var goal: DailyGoal?
    var isLoading = false
    var isSaving = false
    var error: String?
    var saveSuccess = false

    // Editable fields
    var editCalories: String = ""
    var editProtein: String = ""
    var editCarbs: String = ""
    var editFat: String = ""
    var editSugar: String = ""
    var editFiber: String = ""

    func load() async {
        isLoading = true
        do {
            let loaded = try await api.getGoalsForDate(date: Date().apiDateString)
            goal = loaded
            populateFields(from: loaded)
        } catch {
            self.error = "No active goal found"
        }
        isLoading = false
    }

    func save() async {
        isSaving = true
        saveSuccess = false
        error = nil
        do {
            let request = UpdateGoalsRequest(
                calories: Double(editCalories) ?? 0,
                protein: Double(editProtein) ?? 0,
                carbs: Double(editCarbs) ?? 0,
                fat: Double(editFat) ?? 0,
                sugar: Double(editSugar) ?? 0,
                fiber: Double(editFiber) ?? 0
            )
            try await api.updateGoals(request)
            // Reload goals to get the full updated object
            let updated = try await api.getGoalsForDate(date: Date().apiDateString)
            goal = updated
            populateFields(from: updated)
            saveSuccess = true
        } catch {
            self.error = error.localizedDescription
        }
        isSaving = false
    }

    private func populateFields(from goal: DailyGoal) {
        editCalories = "\(Int(goal.calories))"
        editProtein = "\(Int(goal.protein))"
        editCarbs = "\(Int(goal.carbs))"
        editFat = "\(Int(goal.fat))"
        editSugar = "\(Int(goal.sugar))"
        editFiber = "\(Int(goal.fiber))"
    }
}
