import SwiftUI
import Foundation
import Models
import TaskStore

@Observable
@MainActor
final class TaskEditViewModel {
	var title: String
	var body: String
	var dueDate: Date?
	var hasDueDate: Bool
	var linkedMessageId: String?
	var errorMessage: String?

	private let accountId: String
	private let taskStore: TaskStore

	init(
		accountId: String,
		taskStore: TaskStore,
		linkedMessageId: String? = nil,
		title: String = ""
	) {
		self.accountId = accountId
		self.taskStore = taskStore
		self.linkedMessageId = linkedMessageId
		self.title = title
		self.body = ""
		self.dueDate = nil
		self.hasDueDate = false
	}

	var canSave: Bool {
		!title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
	}

	func save() throws {
		let id = UUID().uuidString
		let trimmedBody = body.trimmingCharacters(in: .whitespacesAndNewlines)

		try taskStore.writeTask(
			id: id,
			accountId: accountId,
			summary: title.trimmingCharacters(in: .whitespacesAndNewlines),
			description: trimmedBody.isEmpty ? nil : trimmedBody,
			status: TaskStatus.needsAction.rawValue,
			priority: 0,
			dueDate: hasDueDate ? dueDate : nil,
			deferUntil: nil,
			linkedMessageId: linkedMessageId,
			categories: nil,
			isSomeday: false
		)
	}
}
